PersianGulf
PersianGulf

Reputation: 2885

convert nested list to int or str

I have the following list structure:

the_given_list = [[[1],[2],[3]],[[1],[2],[3]]]

Indeed len(the_given_list) returns 2. I need to make the following list:

the_given_list = [[1,2,3],[1,2,3]]

How to do it?

Upvotes: 1

Views: 89

Answers (5)

Rahul K P
Rahul K P

Reputation: 16081

Use itertools.chain

In [15]: from itertools import chain                                                                                                                                                                        

In [16]: [list(chain(*i)) for i in the_given_list]                                                                                                                                                          
Out[16]: [[1, 2, 3], [1, 2, 3]]

Upvotes: 1

Saurav Sahu
Saurav Sahu

Reputation: 13994

To explain the above answer https://stackoverflow.com/a/57369395/1465553, this list

[[[1],[2],[3]],[[1],[2],[3]]]

can be seen as

[list1, list2]

and,

>> sum([[1],[2],[3]], [])
[1,2,3]
>>> sum([[1],[2],[3]], [5])
[5, 1, 2, 3]

Since the second argument to method sum defaults to 0, we need to explicitly pass empty list [] to it to overcome type mismatch (between int and list).

https://thepythonguru.com/python-builtin-functions/sum/

Upvotes: 1

R4444
R4444

Reputation: 2114

Another solution:

the_given_list = [[[1],[2],[3]],[[1],[2],[3]]]
print([[j for sub in i for j in sub] for i in the_given_list])

Gives me:

[[1, 2, 3], [1, 2, 3]]

Check the original answer on list flattening:

https://stackoverflow.com/a/952952/5501407

Upvotes: 0

AhmadShafiei
AhmadShafiei

Reputation: 11

the_given_list  = [ [ s[0] for s in f ] for f in the_given_list ]

Upvotes: 0

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4199

[sum(x, []) for x in the_given_list]

Flatten the first-order element in the_given_list.

the_given_list = [sum(x, []) for x in the_given_list]
print(the_given_list)

Upvotes: 4

Related Questions