我有以下字典,我只需要打印带有奇数(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.'
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有:
for c in zen:
print (c , zen[c][:])
Run Code Online (Sandbox Code Playgroud)
如果您的密钥是数字:
for i in range(1,len(zen),2):
print(zen[i])
Run Code Online (Sandbox Code Playgroud)
它从1开始,然后以2为步长,所以我只会赔率
另一个较短的方法是列表理解,但是这有点不寻常,因为您实际上不需要列表。
[print(zen[i]) for i in zen if i%2==1]
| 归档时间: |
|
| 查看次数: |
618 次 |
| 最近记录: |