Python基础——列表操作中的append()和extend()方法

append()方法用于在列表末尾添加新的对象;该方法无返回值,但会修改原来的列表 Python List append()方法 | 菜鸟教程

extend()方法用于在列表末尾一次性追加另一个序列中的多个值;该方法没有返回值,但会在已存在的列表中添加新的列表内容 Python List extend()方法 | 菜鸟教程

案例1:

list1 = [1, 2]
list2 = [3, 4]
list3 = [5, 6]

list1.append(list3)
print(list1) # [1, 2, [5, 6]]

list2.extend(list3) 
print(list2) # [3, 4, 5, 6]

案例2:

x = [1, 2, [5, 6]]
xx = [7, 8]
xx.append(x)
print(xx)  # [7, 8, [1, 2, [5, 6]]]

y = [1, 2, [5, 6]]
yy = [7, 8]
yy.extend(y)
print(yy)  # [7, 8, 1, 2, [5, 6]]

案例3:

a = [{"name": "Alice", "age": 18, "sex": "女"}, "ShangHai"]
b = [100, 300]
b.append(a)
print(b) # [100, 300, [{'name': 'Alice', 'age': 18, 'sex': '女'}, 'ShangHai']]

aa = [{"name": "Alice", "age": 18, "sex": "女"}, "ShangHai"]
bb = [100, 300]
bb.extend(aa)
print(bb) # [100, 300, {'name': 'Alice', 'age': 18, 'sex': '女'}, 'ShangHai']

案例4:

a1 = {"name": "Alice", "age": 18, "sex": "女"}
b1 = [100, 200]
b1.append(a1)
print(b1) # [100, 200, {'name': 'Alice', 'age': 18, 'sex': '女'}]

a2 = {"name": "Alice", "age": 18, "sex": "女"}
b2 = [100, 200]
b2.append(a2.keys())
print(b2) # [100, 200, dict_keys(['name', 'age', 'sex'])]

a3 = {"name": "Alice", "age": 18, "sex": "女"}
b3 = [100, 200]
b3.append(a3.values())
print(b3) # [100, 200, dict_values(['Alice', 18, '女'])]

a4 = {"name": "Alice", "age": 18, "sex": "女"}
b4 = [100, 200]
b4.append(a4.items())
print(b4) # [100, 200, dict_items([('name', 'Alice'), ('age', 18), ('sex', '女')])]
aa1 = {"name": "Alice", "age": 18, "sex": "女"}
bb1 = [100, 200]
bb1.extend(aa1)
print(bb1) # [100, 200, 'name', 'age', 'sex']

aa2 = {"name": "Alice", "age": 18, "sex": "女"}
bb2 = [100, 200]
bb2.extend(aa2.keys())
print(bb2) # [100, 200, 'name', 'age', 'sex']

aa3 = {"name": "Alice", "age": 18, "sex": "女"}
bb3 = [100, 200]
bb3.extend(aa3.values())
print(bb3) # [100, 200, 'Alice', 18, '女']

aa4 = {"name": "Alice", "age": 18, "sex": "女"}
bb4 = [100, 200]
bb4.extend(aa4.items())
print(bb4) # [100, 200, ('name', 'Alice'), ('age', 18), ('sex', '女')]

你可能感兴趣的:(Python基础,python,开发语言)