python列表之append与extend方法比较

appendextend是列表的两种添加元素方式,但这两种方式却又有些不同之处。那么不同之处在哪里呢,我们通过对二者的定义和实例来看一看。

list.append()

1、定义:L.append(object) -> None -- append object to end.

2、说明:从定义我们可以看到这是将object原对象添加到list的末尾。

3、栗子:

 1 # 添加一个列表
 2 >>> a = [1, 2, 3, 4, 5]
 3 >>> a.append([6, 7])
 4 >>> a
 5 [1, 2, 3, 4, 5, [6, 7]]
 6 
 7 # 添加一个元组
 8 >>> a.append((8, 9))
 9 >>> a
10 [1, 2, 3, 4, 5, [6, 7], (8, 9)]
11 
12 # 添加一个字典
13 >>> a.append({'dict': 10})
14 >>> a
15 [1, 2, 3, 4, 5, [6, 7], (8, 9), {'dict': 10}]
16 
17 # 添加一个字符串
18 >>> a.append('string')
19 >>> a
20 [1, 2, 3, 4, 5, [6, 7], (8, 9), {'dict': 10}, 'string']
21 
22 # 添加一串数字
23 >>> a.append(1229)
24 >>> a
25 [1, 2, 3, 4, 5, [6, 7], (8, 9), {'dict': 10}, 'string', 1229]

list.extend()

1、定义:L.extend(iterable) -> None -- extend list by appending elements from the iterable.

2、说明:从定义我们可以看到这是将可迭代对象的元素添加到列表的末尾。

3、栗子:

 1 # 添加一个列表
 2 >>> a
 3 [1, 2, 3, 4, 5]
 4 >>> a.extend([6, 7])
 5 >>> a
 6 [1, 2, 3, 4, 5, 6, 7]
 7 
 8 # 添加一个元组
 9 >>> a.extend((8, 9))
10 >>> a
11 [1, 2, 3, 4, 5, 6, 7, 8, 9]
12 
13 # 添加一个字典
14 >>> a.extend({'a': 65, 'b': 66})
15 >>> a
16 [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b']
17 
18 # 添加一个字符串
19 >>> a.extend('cde')
20 >>> a
21 [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e']
22 
23 # 添加一串数字,由于整数是不可迭代的,所以就会报错。
24 >>> a.extend(1229)
25 Traceback (most recent call last):
26   File "<stdin>", line 1, in <module>
27 TypeError: 'int' object is not iterable

猜你喜欢

转载自www.cnblogs.com/cpl9412290130/p/10316336.html
今日推荐