2015-04-02 10 views
0

我有一个嵌套列表分发:重排列表的列表,以便更早列表在后面列出

[ [ 'col1', 
     'col2', 
     'col3', 
     'col4', 
     'some comment', 
     'another comment'], 
    [ 'col1', 
     'col2', 
     'col3', 
     'col4', 
     'someone said something', 
     'a comment here', 
     'more blah blah'] 
] 

我正在寻找一个更优雅和Python的方式直到结束:

[ [ 'col1', 'col2', 'col3', 'col4', 'some comment'], 
    [ 'col1', 'col2', 'col3', 'col4', 'another comment'] ], 
    [ 'col1', 'col2', 'col3', 'col4', 'someone said something'], 
    [ 'col1', 'col2', 'col3', 'col4', 'a comment here'] 
    [ 'col1', 'col2', 'col3', 'col4', 'more blah blah'] 

比我到现在为止所做的还要多。

  • 幸运的是,我的所有内部列表具有相同的4串(又名col1col2, 等)。
  • 我有很多内部列表(不只是2)。
  • 每个内部列表中的前4个字符串后面至少有一个字符串;往往有很多。

回答

0

假设当前列表中的变量称为old_list

base = old_list[0][:4] 
new_list = [] 

for line in old_list: 
    for comment in line[4:]: 
     new_list.append(base + [comment]) 
0

使用for循环和切片:

l = [ [ 'col1', 
     'col2', 
     'col3', 
     'col4', 
     'some comment', 
     'another comment'], 
    [ 'col1', 
     'col2', 
     'col3', 
     'col4', 
     'someone said something', 
     'a comment here', 
     'more blah blah'] 
] 

o = [] 
for e in l: 
    for p in e[4:]: 
     o.append(e[:4]+[p]) 

结果o之中:

[['col1', 'col2', 'col3', 'col4', 'some comment'], 
['col1', 'col2', 'col3', 'col4', 'another comment'], 
['col1', 'col2', 'col3', 'col4', 'someone said something'], 
['col1', 'col2', 'col3', 'col4', 'a comment here'], 
['col1', 'col2', 'col3', 'col4', 'more blah blah']] 

的理解ve上述循环的rsion是:

o = [e[:4]+[p] for p in e[4:] for e in l] 
0

嵌套循环结构是你的愿望,它可以很容易地通过一个嵌套循环理解

[inner[0:4] + [rest] for rest in inner[4:] for inner in in_lst] 

这里唯一的问题是要了解数据的布局处理和预期的布局,并确定哪些映射可以实现它,

即给予

[ [ 'col1', 
     'col2', 
     'col3', 
     'col4', 
     'some comment', 
     'another comment'], 
    [ 'col1', 
     'col2', 
     'col3', 
     'col4', 
     'someone said something', 
     'a comment here', 
     'more blah blah'] 
] 

,除以输入数据的行分成两组

[[['col1', 'col2', 'col3', 'col4'], 
    ['some comment', 'another comment']], 
[['col1', 'col2', 'col3', 'col4'], 
    ['someone said something', 'a comment here', 'more blah blah']]] 

和环比都在第二组项目与第一组项目充实项目