[英]How to enumerate items in a dictionary with enumerate( ) in python
As the title suggests I wanted to enumerate the key and its values (without brackets) in python.正如标题所示,我想枚举 python 中的键及其值(不带括号)。 I tried the following code:
我尝试了以下代码:
example_dict = {'left':'<','right':'>','up':'^','down':'v',}
[print(i,j,a) for (i,j,a) in enumerate(example_dict.items())]
But it doesn't work.但它不起作用。 I want the output to be like this
我希望 output 是这样的
0 left <
1 right >
2 up ^
3 down v
Thank you in advance先感谢您
In this case enumerate returns (index, (key, value))
, so you just need to change your unpacking to for i, (j, a)
, though personally I would use k, v
instead of j, a
in an example.在这种情况下,枚举返回
(index, (key, value))
,因此您只需将解包更改为for i, (j, a)
,尽管我个人会在示例中使用k, v
而不是j, a
。
for i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
BTW, don't use a comprehension for side effects ;顺便说一句,不要使用对副作用的理解; just use a for-loop.
只需使用 for 循环。
As in Alexandre's comment, the code would work like this:正如在 Alexandre 的评论中一样,代码将像这样工作:
for (i, (name, sym)) in enumerate(example_dict.items()):
print(i, name, sym)
A comment about style: while comprehension is really neat when computing values, using it for a loop of printing would work, but would obfuscate the intent of your code, making it less readable.关于风格的评论:虽然在计算值时理解非常简洁,但将其用于循环打印会起作用,但会混淆代码的意图,使其可读性降低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.