Python 三种列表拼接方式的区别(append,extend,+列表脚本操作符)

Python 三种列表拼接方式的区别

使用+号列表脚本操作符

列表B中的元素作为叶子插入到列表A
注:+号只能连接列表和列表,无法连接列表和字符串

listA=['A_h', 'A_d', 'A_c', 'A_s']
listB=['B_h', 'B_d', 'B_c', 'B_s']
listC=listA+listB
print(listC)

拼接结果显示:

['A_h', 'A_d', 'A_c', 'A_s', 'B_h', 'B_d', 'B_c', 'B_s']

append方式

列表B或字符串整体插入到列表A:

listA=['A_h', 'A_d', 'A_c', 'A_s']
listB=['B_h', 'B_d', 'B_c', 'B_s']
listA.append('new element')
print(listA)
listA.append(listB)
print(listA)
['A_h', 'A_d', 'A_c', 'A_s', 'new element']
['A_h', 'A_d', 'A_c', 'A_s', 'new element', ['B_h', 'B_d', 'B_c', 'B_s']]

extend方式

列表B中的元素 或 字符串的单个字符 (包括空格) 作为叶子插入到列表A:
注:效果与之前的+号列表脚本操作符效果一样,但可以连接列表和字符串

listA=['A_h', 'A_d', 'A_c', 'A_s']
listB=['B_h', 'B_d', 'B_c', 'B_s']
listA.extend('new element')
print(listA)
listA.extend(listB)
print(listA)
['A_h', 'A_d', 'A_c', 'A_s', 'n', 'e', 'w', ' ', 'e', 'l', 'e', 'm', 'e', 'n', 't']
['A_h', 'A_d', 'A_c', 'A_s', 'n', 'e', 'w', ' ', 'e', 'l', 'e', 'm', 'e', 'n', 't', 'B_h', 'B_d', 'B_c', 'B_s']

三者使用效果对比还是很明显,大家可以看自己实际需求使用。

猜你喜欢

转载自blog.csdn.net/TommyXu8023/article/details/105275436