我已经看到实际上有两种(可能更多)方法在Python中连接列表:一种方法是使用extend()方法:
a = [1, 2]
b = [2, 3]
b.extend(a)
Run Code Online (Sandbox Code Playgroud)
另一个使用加号(+)运算符:
b += a
Run Code Online (Sandbox Code Playgroud)
现在我想知道:这两个选项中的哪一个是"pythonic"方式进行列表连接,两者之间是否存在差异(我查阅了官方Python教程但未找到任何关于此主题的内容).
我在python中使用链式方法时遇到了这种情况.假设,我有以下代码
hash = {}
key = 'a'
val = 'A'
hash[key] = hash.get(key, []).append(val)
Run Code Online (Sandbox Code Playgroud)
该hash.get(key, [])回报[]和我期待那本词典是{'a': ['A']}.但字典设置为{'a': None}.在进一步查看时,我意识到这是由于python列表而发生的.
list_variable = []
list_variable.append(val)
Run Code Online (Sandbox Code Playgroud)
将list_variable ['A']
设置为但是,在初始声明中设置列表
list_variable = [].append(val)
type(list_variable)
<type 'NoneType'>
Run Code Online (Sandbox Code Playgroud)
我理解和期望list_variable应该包含['A']有什么问题?为什么语句表现不同?