我有两个清单。一个有标题,另一个有详细信息。我在每个项目前面加上一个数字,以帮助我知道哪个细节属于标题。我想打印标题然后打印细节。我怎么能这样做?
在这个例子中,我只想打印单词,而不是数字(索引)
我的代码:
header= ['1', 'header1', '2', 'header2', '3', 'header3', 4, 'header4']
detail= ['1', 'detailA', '1', 'detailB', '2', 'detailA', '3', 'detailA', '4', 'detailA']
for item1 in header:
index=item1
i+=i
print "Header: ", header[i*2-1]
for item2 in detail:
j+=1
print j
if item1==item2:
print "Detail:\n"
print " ", detail[j*2-1]
答案 0 :(得分:1)
你应该在这里创建一个字典:
In [5]: header= ['1', 'header1', '2', 'header2', '3', 'header3', 4, 'header4']
In [6]: detail= ['1', 'detailA', '1', 'detailB', '2', 'detailA', '3', 'detailA', '4', 'detailA']
In [7]: it=iter(header)
In [8]: dic={} #or use collections.defaultdict(list)
#to preserve order use collections.OrderedDict()
In [9]: for ind in it:
head=next(it)
indexes=[i for i,x in enumerate(detail) if x==ind]
for index in indexes:
dic.setdefault(head,[]).append(detail[index+1])
...:
In [10]: dic
Out[10]:
{'header1': ['detailA', 'detailB'],
'header2': ['detailA'],
'header3': ['detailA']}
答案 1 :(得分:0)
如果列表来自第三方,那么您可以将它们转换为更有用的内容:
header= ['1', 'header1', '2', 'header2', '3', 'header3', '4', 'header4']
detail= ['1', 'detailA', '1', 'detailB', '2', 'detailA', '3', 'detailA', '4', 'detailA']
header = [ (header [i], header [i + 1] ) for i in range (0, len (header), 2) ]
detail = [ (detail [i], detail [i + 1] ) for i in range (0, len (detail), 2) ]
for k, v in header:
print ('Header: {}'.format (v) )
print ('Details:')
print ('\n'.join (dv for dk, dv in detail if dk == k) )
print ()
我在标题列表4
中更改为'4'
。我不使用字典来维护标题的顺序。