译(五十五)-Python的append()和extend()有何区别
如有翻译问题欢迎评论指出,谢谢。
偷个懒,这次的清晰易懂就不把第三个长长的回答加进来了。
Python里的列表操作append与extend有什么不同?
Claudiu asked:
- 列表操作
append()和extend()有什么不同?
- 列表操作
Answers:
kender - vote: 5690
append将对象添加到列表末尾。>>> x = [1, 2, 3] >>> x.append([4, 5]) >>> print(x) [1, 2, 3, [4, 5]]extend将列表内元素依次添加。>>> x = [1, 2, 3] >>> x.extend([4, 5]) >>> print(x) [1, 2, 3, 4, 5]Harley Holcombe - vote: 707
append给列表加一个元素,extend则是将列表与另一个列表(或迭代器)进行连接。>>> li = ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> >>> li.append("new") >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new'] >>> >>> li.append(["new", 2]) >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]] >>> >>> li.insert(2, "new") >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]] >>> >>> li.extend(["two", "elements"]) >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements']
What is the difference between Python\'s list methods append and extend?
Claudiu asked:
- What\'s the difference between the list methods
append()andextend()?
列表操作append()和extend()有什么不同?
- What\'s the difference between the list methods
Answers:
kender - vote: 5690
>>> x = [1, 2, 3] >>> x.append([4, 5]) >>> print(x) [1, 2, 3, [4, 5]]extendextends list by appending elements from the iterable.
extend将列表内元素依次添加。>>> x = [1, 2, 3] >>> x.extend([4, 5]) >>> print(x) [1, 2, 3, 4, 5]Harley Holcombe - vote: 707
appendadds an element to a list, andextendconcatenates the first list with another list (or another iterable, not necessarily a list.)
append给列表加一个元素,extend则是将列表与另一个列表(或迭代器)进行连接。>>> li = ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> >>> li.append("new") >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new'] >>> >>> li.append(["new", 2]) >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]] >>> >>> li.insert(2, "new") >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]] >>> >>> li.extend(["two", "elements"]) >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements']


共有 0 条评论