Lua对Python的“Generic For Loop”?

2024-04-26 20:40:58 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我一直在寻找类似于Lua在Python中的“Generic for Loop”的东西。在

我一直在用Python开发一个简单的基于文本的游戏,我也经常使用字典。在

以下是我要找的东西(在Lua中):

Dictionary = {
"Red" = "There is some red paint on the walls.",
"Green" = "There is a little bit of green paint on the floor.",
}

for i, v in pairs(Dictionary) do
print(i, v)
end

它要做的是,浏览字典,然后打印出索引和值。如何在Python中执行类似的操作?在

我知道有这样的情况:

for i in Dictionary: print(i)

但这只是打印索引。我想访问索引和值。比如:

^{pr2}$

感谢任何帮助。在


Tags: thein文本loop游戏fordictionary字典
3条回答

两种方式:

for i, v in Dictionary.items():
    print(i, v) #outputs pairs as key value
for tup in Dictionary.items(): #same thing
    print(tup) # outputs pairs as (key,value)

或者

^{pr2}$

编辑评论回复:

>>> d = {1:1,2:2,3:3,4:4}
>>> for item in d.items(): print(item)

(1, 1)
(2, 2)
(3, 3)
(4, 4)
>>> for key,val in d.items(): print(key,val) 

1 1
2 2
3 3
4 4

这是因为在第一个循环中,item是一个元组,而元组的__repr__包含方括号和逗号,第二个循环将元组拆分为两个独立的变量。print然后在print函数传递的每个参数之间自动添加一个空格分隔符。在

正如两位炼金术士所解释的:

In case it's not entirely clear still, in the tup formulation you'd access the key and value as tup[0] and tup[1], respectively. for key, val in my_dict.items(): ... and for tup in my_dict.items(): key, val = tup is the same setup. The point is you can use tuple unpacking just fine inline in a for loop.

你在找^{}。你只需重复一遍,就可以做到:

for key in my_dict:
    x = my_dict[key]

你想要的是:

^{pr2}$

items方法(或者在Py2中,viewitems或{}来避免生成一个包含dict密钥/值对副本的全新的{})是一种方法:

for k, v in Dictionary.items():  # For performance, use .viewitems() on Py2.7, .items() on Py3.x
    print(k, v)

相关问题 更多 >