我已经尝试了很多次了。
>>> x = [4,5]
>>> y = x.append(7)
>>> print y
None
>>>print x
[4, 5, 7]
这怎么可能?
当我尝试将值存储在新列表
y
中并打印它时,它会产生None
,并且还会更改当前列表`x。
Python 中还有其他方法可以做到这一点吗?
因为函数
append()
修改了列表并返回None
。
完成您想做的事情的最佳实践之一是使用
+
运算符。
让我们以你的例子为例:
>>> x = [4, 5]
>>> y = x + [7]
>>> x
[4, 5]
>>> y
[4, 5, 7]
+
运算符创建一个新列表并保持原始列表不变。
这是可能的,因为
x.append()
是列表 x
的一种方法,可以就地改变列表。不需要返回值,因为该方法所需要做的就是执行副作用。因此,它返回 None
,您可以将其分配给变量 y
。
我认为您想要创建
x
的副本并附加到它:
y = x[:]
y.append(7)
或分配
y
实际创建新列表的列表操作的结果:
y = x + [7]
你可以做
x = [4,5]
y = x + [7]
# x = [4, 5]
# y = [4, 5, 7]
y
是 None
,因为 append()
方法不会返回修改后的列表(来自您期望的代码)。
因此您可以拆分该语句,
y = x.append(7)
进入
x.append(7)
y = x
或使用,
y = x + [7]
第二个语句更清晰,并从
x
创建一个新列表。
请注意:更新
y
不会像第一个语句那样对 x
进行任何更新。如果您想避免这种使用copy.copy
n=[4,7,9,1,56] #original list
n=n+[100]
print(n)
使用扩展,
# Initial list
x = [3, 4]
# Create an empty list to store the result
y = []
# Using extend to add elements to the empty list
# We use list concatenation to create a new list containing the elements of x and the new value (7)
# Then, we extend the empty list y with this new list
y.extend(x + [7])
# Print the original list x and the modified list y
print(x, y)
产生输出:
[3, 4] [3, 4, 7]
[Program finished]