L = ['abc', 'ADB', 'aBe']
L[len(L):]=['a1', 'a2'] # append items at the end...
L[-1:]=['a3', 'a4'] # append more items at the end...
...作品,但 'A2' 在输出丢失:追加到一个列表
['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']
L = ['abc', 'ADB', 'aBe']
L[len(L):]=['a1', 'a2'] # append items at the end...
L[-1:]=['a3', 'a4'] # append more items at the end...
...作品,但 'A2' 在输出丢失:追加到一个列表
['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']
要将项目追加到列表中,您可以使用+
L + ["a1","a2"]
你的第三个分配覆盖“A2”值。
也许你应该使用一个更简单的方法:
L = ['abc', 'ADB', 'aBe']
L += ['a1', 'a2']
L += ['a3', 'a4']
Etc.
使用L.append
(单个元素)或L.extend
(一个序列) - 但绝对没有呼叫玩花哨“分配-TO-切片“技巧(特别是如果你不掌握它们 - )。切片[-1:]
的意思是“最后一个元素包括” - 因此,通过分配该切片,显然“覆盖”了最后一个元素!
使用扩展方法
L = ['abc', 'ADB', 'aBe']
L.extend(['a1', 'a2'])
L.extend(['a3', 'a4'])
为什么不使用Python的名单追加和扩展功能。 – MitMaro 2009-11-21 05:41:52