[英]print multiple values for each key in a dictionary on a new line, preceded by the key
In Python, I have two lists, ids
and gos
and both have the same length (ie equal number of lines), but gos can have multiple elements per line (ie, it is a list of lists) while ids has only 1 element per line 在Python中,我有两个列表,
ids
和gos
都具有相同的长度(即,行数相等),但是gos每行可以有多个元素(即,它是列表的列表),而ids每行仅具有1个元素线
For example: 例如:
ids = ['1','2','3']
gos = [['a','b','c'],['d', 'e'], ['f']]
I want to print out each id in ids as many times as there are go-elements in the gos list followed by one of the corresponding elements from gos list, and each time on a new line. 我想打印每个ID中的ID的次数与gos列表中的go-elements一样多,然后再打印gos列表中的相应元素之一,并且每次都换行。
I hope this clarifies the output I am seeking: 我希望这可以澄清我正在寻找的输出:
'1' 'a'
'1' 'b'
'1' 'c'
'2' 'd'
'2' 'e'
'3' 'f'
Use zip: 使用邮编:
for i,g in zip(ids, gos):
for ge in g:
print i,ge
output: 输出:
1 a
1 b
1 c
2 d
2 e
3 f
You can try these simple nested for loops: 您可以尝试以下简单的嵌套 for循环:
for i, e1 in enumerate(ids):
for e2 in gos[i]:
print e1, e2
Output: 输出:
1 a
1 b
1 c
2 d
2 e
3 f
Note: The enumerate
function is used to keep count of the index, which will be used to access to the corresponding element of gos
. 注意:
enumerate
函数用于保留索引的计数,该索引将用于访问gos
的相应元素。
another way of doing this 另一种方式
from itertools import product,imap
ids = ['1','2','3']
gos = [['a','b','c'],['d', 'e'], ['f']]
for i in imap(product,ids,gos):
for j in i:
print j[0],j[1]
Yet another way of doing it.. 还有另一种方法。
ids = "1 2 3".split()
gos = ['a b c'.split(), 'c d'.split(), ['f']]
import itertools
ig = [zip([i] * len(g), g)
for i, g in zip(ids, gos)]
for i, g in itertools.chain.from_iterable(ig):
print(i, g)
I hope this is an easy way to do that 我希望这是一种简单的方法
for i in range(len(gos)):
for k in gos[i]:
print ids[i], k
Output 产量
1 a
1 b
1 c
2 d
2 e
3 f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.