treashure programming
treashure programming

Reputation: 41

Two dimensional list to one

I have multiple dimension list output I want to turn it to one dimension.

   a = [1,0,3,0,5,0]

   new_list = []

   l = [2,4,6]



   for i in a:
     new_list.append(l)



    print(new_list)

    #[[2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6]]

Upvotes: 0

Views: 69

Answers (3)

DirtyBit
DirtyBit

Reputation: 16772

Using list-comprehension:

s = [[2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6]]

print([x for subl in s for x in subl])

OUTPUT:

[2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6]

Upvotes: 0

virvurtur
virvurtur

Reputation: 11

You really are ought to extend the list, instead of append if you want a flat list to begin with. But if you already have it, the quickest and safest would be to use itertools:

list(itertools.chain.from_iterable(your_list))

Upvotes: 1

dmitryro
dmitryro

Reputation: 3506

You can do it recursively:

def flatten(s):
    if s == []:
        return s
    if isinstance(s[0], list):
        return flatten(s[0]) + flatten(s[1:])
    return s[:1] + flatten(s[1:])

l = [[2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6], [2, 4, 6]]
res = flatten(l)
print(res) # prints [2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6, 2, 4, 6]

Upvotes: 0

Related Questions