【问题标题】:How can i add a list to a list in a dictionary如何将列表添加到字典中的列表中
【发布时间】:2016-10-29 03:26:14
【问题描述】:

我正在努力找出这里出了什么问题我正在尝试将此列表附加到字典键的列表中,但我只得到最后一个。

例如:

pastmoves =['n','w','s','w']
moves = [1,0,1,0]
turnpt = {'pos' : [],
          'moves' : [],
          'lastmove' : []}
pos = [1,1]
opt = [1]


while 5 not in opt:
    if len(pastmoves) > 1:
        if moves.count(1) > 1:
            if pos not in turnpt['pos']:
                turnpt['pos'].append(pos)
                print(turnpt['pos'])
    pos[1] += 1
    print(pos)
    opt[0] += 1
else:
    print(opt)    

我的标准输出显示:

[[1, 1]]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[5]

我希望pos 的每个版本都被附加到turnpt['pos'] 列表中,但这并没有发生,这是为什么呢?

注意:

我的 if 逻辑是嵌套的,因为我需要在每个操作之间完成其他操作,这只是一个工作示例。

【问题讨论】:

  • 你的缩进不正确

标签: python list dictionary while-loop append


【解决方案1】:

使用pos[:] 传递列表pos 的副本。当您追加pos 然后更改它时,它也会在turnpt 中更改,因为它是对列表的引用,并且您的条件永远不会是True。

while 5 not in opt:
    if len(pastmoves) > 1:
        if moves.count(1) > 1:
            if pos not in turnpt['pos']:
                turnpt['pos'].append(pos[:])
                print(turnpt['pos'])

【讨论】:

  • 为了便于阅读,我更喜欢使用pos[:] 来复制列表,因为当我阅读list(pos) 之类的内容时,我希望pos 不是列表,例如一个发电机。我想知道什么更常见?
  • 太棒了!请您解释一下为什么会这样?
  • @juanpa.arrivillaga 我认为这两个都被广泛使用,但我同意你的观点,pos[:] 更便于阅读。
【解决方案2】:

你的问题出在

if pos not in turnpt['pos']:
    turnpt['pos'].append(pos)

您检查是否 pos in not in turnpt['pos'],然后附加它,因此之后 pos not in turnpt['pos'] 永远不会为真。举例说明:

a = [1,1]
b = [[1,1]]
c = [a]

a in b == True
a in c == True

a[0] = 2

a in b = False
a in c == True

如果你附加一个 pos 的副本,你有预期的行为:

turnpt['pos'].append(pos[:])

或者,如果 pos 此后不再更改,则使用元组代替是一个好习惯

turnpt['pos'].append(tuple(pos))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2018-08-27
    • 2020-09-18
    • 2015-04-02
    • 1970-01-01
    相关资源
    最近更新 更多