[英]How to read multi-value library with for loop in python
Assume that CSV file has this content:假设 CSV 文件有这个内容:
Main1,Name1,Name2,Name3,Name4
Main2,NameA,NameB
Main3,Name11,Name12,Name13
When I read it as library result is following:当我阅读它作为库结果如下:
{'Main1': ['Name1', 'Name2', 'Name3', 'Name4'],
'Main2': ['NameA', 'NameB'],
'Main3': ['Name11', 'Name12', 'Name13']}
When I turn to particular item/value like a['Main3'][2]
I'll get answer 'Name13'
.当我转向像
a['Main3'][2]
这样的特定项目/值时,我会得到答案'Name13'
。 But the values ('Name's') are unknown number and I would like to read them all individually in eg for loop.但是值('Name's')是未知数,我想在例如for循环中单独读取它们。 If I read like this:
如果我这样读:
for rows in a:
print(rows)
I will get answer:我会得到答案:
Main1
Main2
Main3
But I would like to modify code something like:但我想修改如下代码:
for rows in a:
print(rows)
for values in rows:
print(values)
But result is erroneous.但结果是错误的。 I expect to see something like this:
我希望看到这样的事情:
'Main1'
'Name1'
'Name2'
'Name3'
'Name4'
'Main2'
'NameA'
'NameB'
'Main3'
'Name11'
'Name12'
'Name13'
And I cannot figure out how to modify my code.而且我不知道如何修改我的代码。 Would you please help me?
你能帮帮我吗? Thanks!
谢谢!
As you can see a
is a dictionary.如您所见
a
是一本字典。 so you want each key and the values, So, Try this:所以你想要每个键和值,所以,试试这个:
for k,v in a.items():
print(k, *v, sep='\n')
try this:尝试这个:
for rows in a:
print(rows)
for values in a[rows]:
print(' ',values)
Try to do like this.尝试这样做。
for rows in a:
print(rows)
for values in a[rows]:
print(values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.