Python 追加到列表-无结果
数据:Python 追加到列表-无结果,python,append,Python,Append,数据: lis_t = [['q', 'w', 'e'],['r', 't', 'y']] None [None, ['r', 't', 'y']] 预期结果: lis_t = [['q', 'w', 'e', 'u'],['r', 't', 'y']] lis_t = [['q', 'w', 'e'],['r', 't', 'y']] lis_t[0] = lis_t[0].append('u') print(lis_t[0]) print(lis_t) 问题描述:我正试图附加到上面的
lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
None
[None, ['r', 't', 'y']]
预期结果:
lis_t = [['q', 'w', 'e', 'u'],['r', 't', 'y']]
lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
lis_t[0] = lis_t[0].append('u')
print(lis_t[0])
print(lis_t)
问题描述:我正试图附加到上面的列表中,但是无法附加相同的内容,因为它不知何故导致没有结果。请帮助我理解我做错了什么
编写的代码:
lis_t = [['q', 'w', 'e', 'u'],['r', 't', 'y']]
lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
lis_t[0] = lis_t[0].append('u')
print(lis_t[0])
print(lis_t)
输出:
lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
None
[None, ['r', 't', 'y']]
这样做
lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
lis_t[0].append('u')
print(lis_t)
lis\u t[0]。追加('u')
这将返回None
值,然后您将其分配给lis\u t[0]
这就是您获得None
值的原因
lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
lis_t[0].append('u')
print(lis_t)
Python函数在调用时总是返回值。如果没有提供返回值,它将返回
None
pythonlist.append()
是一个没有返回值的函数,因此调用时将返回None
您正在做的是将list.append()
方法调用分配给lis\t[0]
因此,在你的情况下,正确的方法是
lis_t[0].append('u')
除了
list_t[0].append('u')
您可以这样做(如果您喜欢使用“+”)
或
结果总是这样
print(list_t[0])
>>> ['q', 'w', 'e', 'u']
istead of
lis\u t[0]=lis\u t[0]。append('u')
writelis\u t[0]。append('u')
也许您可以添加一些解释性文本,解释为什么这种方法有效以及为什么原始方法无效。