Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert nested list into list containing strings in python?

Tags:

python

I was trying to read a csv file:

SigGenelist = []
Sig = csv.reader(open('Genelist.csv'))
for row in Sig:
    SigGenelist.append(row)
print (SigGenelist)

the print out was like:

[['x'], ['0610010K14Rik'], ['0610011F06Rik'], ['1110032F04Rik'], ['1110034G24Rik'], ...

so I got a nested list, but I would like to have a list with each element as string, something like:

['x', '0610010K14Rik', '0610011F06Rik', '1110032F04Rik', '1110034G24Rik', ...

I tried to convert element into string like:

SigGenelist = []
Sig = csv.reader(open('Genelist.csv'))
for row in Sig:
    row = str(row) # try to change row into string instead of list
    SigGenelist.append(row)
print (SigGenelist)

but did not get what I would like to...

["['x']", "['0610010K14Rik']", "['0610011F06Rik']", "['1110032F04Rik']","['1110034G24Rik']"...

Any suggestion?

like image 230
Jun Avatar asked May 16 '26 19:05

Jun


2 Answers

Instead of append try using + operator, change your line

...
SigGenelist.append(row)
...

to use +=:

...
SigGenelist += row
...

Append is used to add a single element to your list, while += and extend is used to copy the list on the right hand side to the left hand side. And since extend is more expensive due to an additional function call (not that it matters, difference is very small), += is a good way in your situation.

like image 114
umutto Avatar answered May 19 '26 07:05

umutto


Try this:

my_list = [[1], [2], [3], [4], [5], [6]]
print [item for sublist in my_list for item in sublist]

This is a list comprehension that will flatten a list of lists into a single list.

Or, maybe the simpler option is not appending, but adding the rows to the list.

SigGenelist = []
Sig = csv.reader(open('Genelist.csv'))
for row in Sig:
    SigGenelist += row
print (SigGenelist)

.append will add the entire list to the end of the list, resulting in the nested lists. += will just concatenate the lists, making it a list of depth 1!

like image 45
Christopher Apple Avatar answered May 19 '26 08:05

Christopher Apple



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!