リスト内の数字の合計【Python】for文とリスト操作の続きです
a = [23,17,13,42,91,83,156,248]
というリストがあるとき、13の倍数を取得します。
方法としてはfor文で取り出すことが考えられますが、取得された数値をprintするだけでなく、次の作業がしやすいリストの形で出力するにはどうすれば良いでしょうか
結果として
13
91
156
と改行した文字列でただ出てくるよりも、
[13,91,156]
とリストで整理されて出力されたほうが、次の作業がしやすいはずです。
ここではfor文で取得した値を"append"で追加するメソッドを使用します
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
a = [23,17,13,42,91,83,156,248] | |
# 13の倍数を取得 | |
b =[] | |
for i in a: | |
if i % 13 ==0: | |
b.append(i) | |
print (b) |
b =[]
#空のリストを作成
for i in a:
#for文でリストaの要素数で繰り返し
if i % 13 ==0:
#a[i]を13で割ったときの余りが0であれば
b.append(i)
#空のリストbにa[i]を追加
print (b)
もちろん繰り返し回数を"len(a)"で取得しても良いです
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
a = [23,17,13,42,91,83,156,248] | |
b = [] | |
for i in range(len(a)): | |
if a[i] % 13 ==0: | |
b.append(a[i]) | |
print(b) |
<<< リスト内の数字の合計【Python】for文とリスト操作
0 件のコメント:
コメントを投稿