これは私のリストです。 list1
のすべての番号をlist2
のすべての番号に追加するにはどうすればよいですか?リストからすべての番号を番号に追加するにはどうすればよいですか?
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
outcomelist = [7,8,9,10,11,8,9,11,12,9,10,11,12,13,10,11,12,13,14,1,12,13,14,15]
これは私のリストです。 list1
のすべての番号をlist2
のすべての番号に追加するにはどうすればよいですか?リストからすべての番号を番号に追加するにはどうすればよいですか?
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
outcomelist = [7,8,9,10,11,8,9,11,12,9,10,11,12,13,10,11,12,13,14,1,12,13,14,15]
使用zipビルドイン機能とlist comprehension
[x + y for x, y in zip([1,2,3,4,5], [6,7,8,9,10])]
>>> [7, 9, 11, 13, 15]
それとも、すべてにすべてを合計したい場合zipping
をしない:
[x + y for x in [1,2,3,4,5] for y in [6,7,8,9,10]]
>>> [7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13, 10, 11, 12, 13, 14, 11, 12, 13, 14, 15]
これは役に立ちましたが、もし最終的なリストがこのように見えるようなら、 [7,8,9,10,11,8,9,11,12,9,10,11,12,13,10 、11,12,13,14,1,12,13,14,15]? –
@MarekTran、updated –
あなたが構築したい場合新しいリストは、あなたが行うことができます:
list3 = [x + y for x, y in zip(list1, list2)]
何をしたいあなたはLIST2を更新している場合は、インデックスにアクセスし、リストを更新するために列挙を使用しcanalso:
for idx, tuple in enumerate(zip(list1, list2)):
list2[idx] = tuple[1] + tuple[0]
これは役に立ちましたが、最終的なリストがこのように見えるようにしたい場合[7,8,9,10,11,8,9,11,12,9,10,11,12,13,10、 11,12,13,14,1,12,13,14,15]? –
のpython3
add=lambda x,y:x+y
list(map(add,list1,list2))#[7, 9, 11, 13, 15]
import operator
list(map(operator.add,list1,list2))#[7, 9, 11, 13, 15]
リストcomperhension:
[x+y for x,y in zip(list1,list2)]#[7, 9, 11, 13, 15]
[sum([x,y]) for x,y in zip(list1,list2)]#[7, 9, 11, 13, 15]
使用itertools.product
を使用して、可能なすべてのペアを作成します。
>>> import itertools
>>> list1 = [1,2,3,4,5]
>>> list2 = [6,7,8,9,10]
>>> [x + y for (x,y) in itertools.product(list1, list2)]
>>> resultlist
[7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13, 10, 11, 12, 13, 14, 11, 12, 13, 14, 15]
あなたは複数のリストにこれを拡張することができます。リストの
>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list3 = [7,8,9]
>>> [x + y + z for (x, y, z) in itertools.product(list1, list2, list3)]
あるいは可変数:そこ
>>> [sum(items) for items in itertools.products(*list_of_lists)]
こんにちは、stackoverflowのコミュニティへようこそ。この質問は既に回答済みです。http://stackoverflow.com/questions/1720421/how-to-append-list-to-second-list-concatenate-lists – ssuperczynski
あなたの質問は何ですか?これまでに試したコードで質問を更新したり、質問に[最小限の、完全で検証可能な例(http://stackoverflow.com/help/mcve)]を追加できますか? – Kasramvd
あなたは '[1,2,3,4,5,6,7,8,9,10]'、 '55 '、' [7,9,11,13,15 ] '... – TigerhawkT3