gpt4 book ai didi

python - 当我 append 到 Python 中的列表时出现奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:14 24 4
gpt4 key购买 nike

我正在寻找 Josephus_problem ,但结果不是我的预期。为什么?

def J(n,x):
li=range(1,n+1)
k=0
res=[]
while len(li)>1:
k= (x+k-1) % len(li)
li.pop(k)
res.append(li)
#print li
return res

print J(5,3)

预期输出:

[1, 2, 4, 5]

[2, 4, 5]

[2, 4]

[4]

实际输出:

[[4], [4], [4], [4]]

最佳答案

您需要在此处 append 列表的副本:

res.append(li[:]) # <-- not res.append(li) !!!

list 是 Python 中的可变数据结构的真正原因。看看这个片段

>>> l = [1,2,3]
>>> p = [l,l,l]
>>> p
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> l.pop()
3
>>> p
[[1, 2], [1, 2], [1, 2]]

关于python - 当我 append 到 Python 中的列表时出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12453396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com