2017-03-28 9 views

答えて

7

(あなたが[1,2,4,5,6,3]を意味している場合)、スライスの割り当てを使用:

>>> list_one = [1,2,3] 
>>> list_two = [4,5,6] 
>>> list_one[2:2] = list_two 
>>> list_one 
[1, 2, 4, 5, 6, 3] 
+0

ワウ!私はそれが可能であることを知らなかった!あなたは毎日何か新しいことを学びます... – Julien

+0

@Julien、チュートリアル(https://docs.python.org/3/tutorial/introduction.html#lists)で説明しています。もしあなたがそうしなければ、あなたはそれを読むことをお勧めします。 – falsetru

3

あなたが代わりにこの結果[1,2,4,5,6,3]を望んでいませんか?もしそうなら、これを試してみてください。

list_one[:2]+list_two+list_one[2:] 
1

あなたがこの方法を試すことができます。

ActivePython 2.7.13.2713 (ActiveState Software Inc.) based on 
Python 2.7.13 (default, Jan 18 2017, 15:40:43) [MSC v.1500 64 bit (AMD64)] on wi 
n32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> list_one = [1,2,3] 
>>> list_two = [4,5,7] 
>>> from itertools import chain 
>>> result = [ elem for elem in chain(list_one[0:2], [2,3], list_one[2:], list_two)] 
>>> 
>>> result 
[1, 2, 2, 3, 3, 4, 5, 7] 
>>> result1 = list(chain(list_one[0:2], [2,3], list_one[2:], list_two)) 
>>> result1 
[1, 2, 2, 3, 3, 4, 5, 7] 
+1

リスト内包表記の代わりに 'list'を使うことができます:' list(chain(list_one [0:2]、[2,3]、list_one [2:]、list_two)) ' – falsetru

+0

はい、これも可能です。 – kvivek

関連する問題