>>> a = []
>>> my_list = []
>>> my_list += 'abcd'
>>> my_list
['a', 'b', 'c', 'd']
>>> my_list += (1,2,3,4)
>>> my_list.extend(list('python'))
>>> my_list
['a', 'b', 'c', 'd', 1, 2, 3, 4, 'p', 'y', 't', 'h', 'o', 'n']
>>> my_list += 1234
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
# In case of dictionary it will extend keys of dictionary.
>>> my_list += my_dict
>>> my_list
['a', 'b', 'c', 'd', 1, 2, 3, 4, 'p', 'y', 't', 'h', 'o', 'n', 'key2', 'ke1']
的+=
運營商擴展提供給它的任何sequence
(它是iterable
)。
>>> angles = []
>>> angles.append(raw_input("Enter an angle: "))
Enter an angle: 20
>>> angles.append(raw_input("Enter an angle: "))
Enter an angle: 50
>>> angles.append(raw_input("Enter an angle: "))
Enter an angle: 25
>>> angles
['20', '50', '25']
您應該使用append
內置函數來添加元素列出。
append(...)
L.append(object) -- append object to end
'+ ='運營商實際上是調用'list.extend',它(這裏的字符串)追加迭代的每個項目的列表。 – 2014-12-02 12:46:38