gpt4 book ai didi

python - python中的字典和栈问题

转载 作者:行者123 更新时间:2023-12-01 06:16:07 24 4
gpt4 key购买 nike

我制作了一本字典,并将字典的键放入列表中。我的列表包含这样的元素:

s =  [((5, 4), 'South', 1), ((4, 5), 'West', 1)]

我从中做了一个字典:

child = dict((t[0], t[1]) for t in s)

keys = child.keys()
print keys

输出为:[(4, 5), (5, 4)]

现在我需要将 (4,5) 和 (5,4) 放入堆栈中。我该怎么办?

我尝试过,但是当我从堆栈中弹出时,它会同时给我两个元素。就像 stack.pop() - 输出是:[(4, 5), (5, 4)]。我想逐一弹出... (4,5) 然后 (5,4)

最佳答案

您可以将列表用作堆栈:

stack = list(child.keys())
print stack.pop()
print stack.pop()

结果:

(5, 4)(4, 5)

Important note: the keys of a dictionary are not ordered so if you want the items in a specific order you need to handle that yourself. For example if you want them in normal sorted order you could use sorted. If you want them to pop off in reverse order from the order they were in s you could skip the conversion to a dictionary and just go straight from s to your stack:

stack = [x[0] for x in s]
print stack.pop()
print stack.pop()

结果:

(4, 5)(5, 4)

关于python - python中的字典和栈问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3273533/

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