[a] + [b]和[a] .extend([b])有什么区别? [英] What's the difference between [a] + [b] and [a].extend([b])?

查看:394
本文介绍了[a] + [b]和[a] .extend([b])有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中有两种将列表合并在一起的方法:

There are 2 ways to merge lists together in Python:

  1. ['a', 'b', 'c'] + ['x', 'y', 'z']

['a', 'b', 'c'].extend(['x', 'y', 'z'])

这两种方法有什么区别?

What's the difference between the 2 methods?

串联两个以上列表的Pythonic方法是什么?

What's the more Pythonic way of concatenating more than 2 lists?

['a', 'b', 'c'] + [1, 2, 3] + ['x', 'y', 'z']

gucci_list = ['a', 'b', 'c']
gucci_list.extend([1, 2, 3])
gucci_list.extend(['x', 'y', 'z'])


如何将两者结合在一起?


How about combining both?

['a', 'b', 'c'].extend([1, 2, 3] + ['x', 'y', 'z'])

推荐答案

第一条语句从两个匿名列表中创建一个新列表,并将其存储在变量new_list中:

The first statement creates a new list out of two anonymous lists and stores it in the variable new_list:

new_list = ['a', 'b', 'c'] + ['x', 'y', 'z']
#['a', 'b', 'c', 'x', 'y', 'z']

第二个语句创建一个匿名列表['a','b','c'],并将另一个匿名列表附加到其末尾(现在,第一个列表为['a', 'b', 'c', 'x', 'y', 'z']). 但是,该列表仍然是匿名的,以后无法访问.由于方法extend不返回任何内容,因此赋值后变量的值为None.

The second statement creates an anonymous list ['a','b','c'] and appends another anonymous list to its end (now, the first list is ['a', 'b', 'c', 'x', 'y', 'z']). However, the list is still anonymous and cannot be accessed in the future. Since the method extend returns nothing, the value of the variable after the assignment is None.

new_list = ['a', 'b', 'c'].extend(['x', 'y', 'z'])
#None

通过首先命名列表然后对其进行更改,可以使第二条语句变得有用:

The second statement can be made useful by first naming the list and then altering it:

old_list = ['a', 'b', 'c']
old_list.extend(['x', 'y', 'z']) # Now, the old list is a new list

这篇关于[a] + [b]和[a] .extend([b])有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆