2014-03-19 66 views
1

我的任务是将列表合并为一个列表。例如:与各种列表合并

all_lst = [[2, 7, 10], [0, 4, 6], [3, 11]] 
>>> [0, 2, 3, 4, 6, 7, 10, 11] 

我已经定义:

def merge(left, right): 
    results = [] 
    while left and right: 
     if left[0]< right[0]: 
      results.append(left[0]) 
      left.remove(left[0]) 
     else: 
      results.append(right[0]) 
      right.remove (right[0]) 
    results.extend(left) 
    results.extend(right) 
    return results 

def merge_lists(all_lst): 
    for i in range(len(all_lst)): 
     A = merge(all_lst[i], all_lst[ i+1]) 
     new = all_lst[i+2:] 
     B = merge(list(A), list(new)) 
    return B 

但是我对IDLE给出:

Traceback (most recent call last): 
    File "<pyshell#162>", line 1, in <module> 
    print(merge_lists(all_lst)) 
    File "<pyshell#161>", line 5, in merge_lists 
    B = merge(list(A), list(new)) 
    File "<pyshell#110>", line 4, in merge 
    if left[0]< right[0]: 
TypeError: unorderable types: int() < list() 

我真的很感激,如果你可以告诉我什么是错的。谢谢〜!

+0

[在Python平展浅列表]的可能重复(http://stackoverflow.com/questions/406121/flattening -a-shallow-list-in-python) –

回答

1

不要试图重新发明weel。从itertools使用chain,像这样:作为你的结果需要订购所需

>>> import itertools as it 
>>> i = [[2, 7, 10], [0, 4, 6], [3, 11]] 
>>> sorted(it.chain(*i)) 
[0, 2, 3, 4, 6, 7, 10, 11] 

的排序通话。

+0

weel是否已经由Python定义了? – user3251511

1

all_lst是列表的列表,然后,当你做

new = all_lst[i+2:] 

new也将是(因为名单切片)列表的列表,然后当你这样做:

B = merge(A, new) # cast to list is not necessary, since both are already lists 

在线

if left[0]< right[0]: 

您正在访问的第一个元素。在列表A中,第一个元素将是整数,但在列表new(列表列表)中,第一个元素将是列表。这就是为什么你得到这个错误。

注:

  • 我会建议你使用调试器或打印语句,看看发生了什么事在你的程序。
1

reduce使用:

sorted(reduce(lambda r,x:r+x,all_lst[1:],all_lst[0])) 

使用list comprehensionextend

result = all_lst[0] 
[result.extend(i) for i in all_lst[1:]] 
print sorted(result)