为什么列表不变?
问题描述:
我试图在有序列表中添加一个值,但该列表将不会改变:为什么列表不变?
def insert(V, x):
if len(V)!=0:
for i in range(0 , len(V)-1):
if (V[i]<=x)and(V[i+1]>=x):
V=V[0:i+1]+[x]+V[i+1:len(V)]
print("\nExpected: \n"+ repr(V))
return
V=V+[x]
return
我有这样的:
V=[1,2,3,4,5,6,7,8,9,10]
insert(V, 6)
print("\nResult: \n"+ repr(V))enter code here
,这是结果:
Expected:
[1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10]
Result:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
我可以解决问题设置V作为返回,但我希望该功能在列表上工作。
答
你在做什么可以简单地用list.insert
完成。
至于为什么你的功能不工作,你需要更新使用全片分配原来的列表,以便传递给函数列表是通过电流参考V
更新:
...
V[:] = V[0:i+1] + [x] + V[i+1:len(V)]
#^
请注意RHS(右手侧)是一个新的列表对象。单独指派给V
将名称/变量重新绑定到新的列表对象。但是,使用切片分配可确保使用新列表中的值更新原始列表。
答
你可以你的价值只是追加到列表中,并随后对其进行排序
l.append(值)
l.sort()
答
到位您的函数不改变V
。
V=V[0:i+1]+[x]+V[i+1:len(V)]
这条线之后,V
不再是传递给函数列表的引用,但另一个列表。此行不会更改第一个列表,但会创建一个新列表。
您必须return V
然后得到结果或调用V
的方法,例如list.insert()
。
答
正如其他人指出的那样,您并未修改原始列表。 (相反,你创建一个新的列表,然后也不回了。)
这里有一个解决方案,它利用list.insert
优势,以修改现有的列表:
def insert(lst, value):
'''Insert a value into a sorted list in-place, while maintaining sort order'''
for i, x in enumerate(lst):
if x > value:
lst.insert(i, value)
return
# fallback, in case this is the new largest
lst.append(value)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
insert(a, 6)
print(a) # [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10]
编辑
更多但可能难以阅读:
def insert(lst, value):
lst.insert(next((i for i, x in enumerate(lst) if x > value), len(lst)), value)
可能的重复[python;修改列表中的函数](https://stackoverflow.com/questions/22054698/python-modifying-list-inside-a-function) – AChampion
是否有你不能使用'list.insert()'的原因? –
'''v。插入(索引,值)''' –