Skip to main content
 首页 » 编程设计

python之仅打印奇数字典键及其项

2025年05月04日24lori

我有以下字典,我只需要打印奇数(1、3 ...)的字典。我该怎么做呢?

zen = { 
    1: 'Beautiful is better than ugly.', 
    2: 'Explicit is better than implicit.', 
    3: 'Simple is better than complex.', 
    4: 'Complex is better than complicated.', 
    5: 'Flat is better than nested.', 
    6: 'Sparse is better than dense.', 
    7: 'Readability counts.', 
    8: 'Special cases aren't special enough to the rules.', 
    9: 'Although practicality beats purity.', 
   10: 'Errors should never pass silently.' 
   } 

到目前为止我有:

for c in zen: 
print (c , zen[c][:]) 

请您参考如下方法:

如果你的键是数字:

for i in range(1,len(zen),2): 
    print(zen[i]) 

它从 1 开始,步进为 2,所以我只会做赔率

正如评论中的用户指出的那样,有时并非所有键都存在:

for i in zen: 
    if (i%2 == 0): 
         print(zen[i]) 

另一种更短的方法是列表理解,但是它有点不寻常,因为您真的不需要列表。

[print(zen[i]) for i in zen if i%2==1]