Jun
Jun

Reputation: 319

How to convert nested list into list containing strings in 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?

Upvotes: 3

Views: 2442

Answers (5)

eguaio
eguaio

Reputation: 3954

Use the sum builtin function, since csv.reader returns a generator, the following code will do the job:

Sig = csv.reader(open('Genelist.csv'))
SigGenelist = sum(Sig, []) 

Upvotes: 0

Jared Goguen
Jared Goguen

Reputation: 9010

This might be idiomatic:

from itertools import chain
csv_reader = csv.reader(open('Genelist.csv'))
SigGeneList = list(chain.from_iterable(csv_reader))

Upvotes: 1

umutto
umutto

Reputation: 7690

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.

Upvotes: 3

gold_cy
gold_cy

Reputation: 14216

Change this:

SigGenelist.append(row)

To this:

SigGenelist.extend(row)

Upvotes: 1

Christopher Apple
Christopher Apple

Reputation: 401

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!

Upvotes: 1

Related Questions