1

I am tasked to merge the lists into a single one. For example:

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

I have defined:

 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

and

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

However I am given by 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()

I would really appreciate it if you could tell me what's wrong. Thanks~!

user3251511
  • 177
  • 1
  • 3
  • 15
  • possible duplicate of [Flattening a shallow list in Python](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – Matthew Trevor Mar 19 '14 at 04:57

3 Answers3

1

all_lst is a list of lists, then, when you do

new = all_lst[i+2:]

new will also be a list of lists (because of list slicing), then when you do:

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

in the line

if left[0]< right[0]:

you are accessing to the first elements. In the list A the first element will be an integer, but in the list new (list of lists) the first element will be a list. That's why you are getting that error.

Note:

  • I would recommend you to use a debugger or print statements to see what's happening in your program.
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

Don't try to re-invent the weel. Use chain from itertools, like this:

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

The sorted call is required as your result needs to be ordered.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1

Using reduce:

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

Using list comprehension and extend:

result = all_lst[0]
[result.extend(i) for i in all_lst[1:]]
print sorted(result)
venpa
  • 4,268
  • 21
  • 23