-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
集合、列表、元祖集合类集合类
Description
连接列表有两种方式:+
和extend
,元组只有一种:+
,由于元祖本身是只读的,没有extend
方法
a = [1,5,7,9,6]
b = [2,3,3,6,8]
c = (1,2,3)
d = (2,3,3,4)
print(a + b) ## [1, 5, 7, 9, 6, 2, 3, 3, 6, 8]
print(c + d) ## (1, 2, 3, 2, 3, 3, 4)
a.extend(b)
print(a) ## [1, 5, 7, 9, 6, 2, 3, 3, 6, 8]
差异:
+
不会改变参与连接的列表的值,但extend
方法可以改变a列表的值+
两侧要么都是元组,要么都是列表。但是列表的extend
方法可以将一个元组添加列表后面
a.extend(c)
print(a) ## [1, 5, 7, 9, 6, 2, 3, 3, 6, 8, 1, 2, 3]
#print(a + c) ## TypeError: can only concatenate list (not "tuple") to list
print(c + d) ## (1, 2, 3, 2, 3, 3, 4)
Metadata
Metadata
Assignees
Labels
集合、列表、元祖集合类集合类