Python的列表方法追加和扩展有什么区别?
2022-09-05 00:44:37
列表方法和 ?append()
extend()
列表方法和 ?append()
extend()
append
将元素添加到列表中。 将第一个列表与另一个列表/可迭代列表连接起来。extend
>>> xs = ['A', 'B']
>>> xs
['A', 'B']
>>> xs.append("D")
>>> xs
['A', 'B', 'D']
>>> xs.append(["E", "F"])
>>> xs
['A', 'B', 'D', ['E', 'F']]
>>> xs.insert(2, "C")
>>> xs
['A', 'B', 'C', 'D', ['E', 'F']]
>>> xs.extend(["G", "H"])
>>> xs
['A', 'B', 'C', 'D', ['E', 'F'], 'G', 'H']