Python apend & extend 使用说明
列表操作
append()函数
a.append(b):是将b原封不动的追加到a的末尾上,会改变a的值,其中,b可为列表、元组、字符串、一串数/字符/字符串
append 列表
a = [1, 2, 3] b = ['a','b'] a.append(b) print(a) # [1, 2, 3, ['a', 'b']]
append 元组
a = [1, 2, 3] b = ('a','b') a.append(b) print(a) # [1, 2, 3, ('a', 'b')]
append 字符串
a = [1, 2, 3] b = 'nice' a.append(b) print(a) # [1, 2, 3, 'nice']
一串数/字符/字符串
会将b转化为元组追加到a的末尾上
数字
a = [1, 2, 3] b = 9,6 a.append(b) print(a) # [1, 2, 3, (9, 6)]
字符
a = [1, 2, 3] b = 'a','b' a.append(b) print(a) # [1, 2, 3, ('a', 'b')]
字符串
a = [1, 2, 3] b = 'nice','hi' a.append(b) print(a) # [1, 2, 3, ('nice', 'hi')]
extend()函数
a.extend(b):是将b拆开后追加到a的末尾上,会改变a的值,其中,b可为列表、元组、字符串、一串数/字符/字符串
列表
a = [1, 2, 3] b = ['a','b'] a.extend(b) print(a) # [1, 2, 3, 'a', 'b']
元组
a = [1, 2, 3] b = ('a','b') a.extend(b) print(a) # [1, 2, 3, 'a', 'b']
字符串
a = [1, 2, 3] b = 'nice' a.extend(b) print(a) # [1, 2, 3, 'n', 'i', 'c', 'e']
一串数/字符/字符串
数字
a = [1, 2, 3] b = 9,6 a.extend(b) print(a) # [1, 2, 3, 9, 6]
字符
a = [1, 2, 3] b = 'a','b' a.extend(b) print(a) # [1, 2, 3, 'a', 'b']
字符串
a = [1, 2, 3] b = 'nice','word' a.extend(b) print(a) # [1, 2, 3, 'nice', 'word']
说明:字符串和元组中都没有append()和extend()函数
a = [1, 2, 3] b = 'nice','word' tt = {'name':'令狐冲','age':25} a.extend(tt) print(a) # [1, 2, 3, 'name', 'age']
字典extend 只进行 key 的 extend
a = [1, 2, 3] b = 'nice','word' tt = {'name':'令狐冲','age':25} a.append(tt) print(a) #[1, 2, 3, {'name': '令狐冲', 'age': 25}]
对字典进行append KV 作为整体进来了