在字典上迭代

2024-09-28 23:19:03 发布

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

使用print(i, j)print(i)的两个设置返回相同的结果。有这样的情况吗 应该在另一个上面使用还是可以互换使用?

desc = {'city': 'Monowi', 'state': 'Nebraska', 'county':'Boyd', 'pop': 1}

for i, j in desc.items():
 print(i, j)

for i in desc.items():
 print(i)

for i, j in desc.items():
 print(i, j)[1]

for i in desc.items():
 print(i)[1]

Tags: incityfor情况itemspopdescstate
2条回答

如果删除打印中的括号,则两者都不同,因为您使用的是python 2X

desc = {'city': 'Monowi', 'state': 'Nebraska', 'county':'Boyd', 'pop': 1}

for i, j in desc.items():
 print i, j 

for i in desc.items():
 print i

输出

county Boyd
city Monowi
state Nebraska
pop 1
('county', 'Boyd')
('city', 'Monowi')
('state', 'Nebraska')
('pop', 1)

items()返回一个视图对象,该对象允许您迭代(key, value)元组。所以基本上你可以像处理元组那样操作它们。document可能有助于:

iter(dictview) Return an iterator over the keys, values or items (represented as tuples > of (key, value)) in the dictionary.

另外,我认为print(i, j)[1]在Python 3中会导致错误,因为print(i, j)返回None

相关问题 更多 >