0

我有两个清单。一个有标题,另一个有细节。我在每个项目前放了一个数字,以帮助我知道哪个细节属于标题。我想打印标题,然后是详细信息。我怎样才能做到这一点?

在这个例子中,我只想打印单词,而不是数字(索引)

我的代码:

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]
4

2 回答 2

1

You should probably create a dictionary here:

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']}
于 2013-02-02T23:59:59.723 回答
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'. 我不使用字典来维护标题的顺序。

于 2013-02-03T04:21:16.797 回答