So I have a list of tuples, for example [('GGG',), ('AAA',), ('BBB',)]
and I want to convert it into a list of strings: ['GGG' , 'AAA', 'BBB']
.
I have tried using a for loop with the join method but cannot get it to work. Any help would be appreciated, Thanks.
Use chain.from_iterable
from itertools
eg
from itertools import chain
x = [('GGG',), ('AAA',), ('BBB',)]
print(list(chain.from_iterable(x)))
output
['GGG', 'AAA', 'BBB']
The use of list
is only to allow printing the output. It forces the lazy object returned from chain.from_iterable
to be evaluated immediately. You don't need it if you will later iterate over object.
There are multiple ways you can achieve this. If array is z = [('GGG',), ('AAA',), ('BBB',)]
, then:
1) Using zip
: list(list(zip(*z))[0])
well the other ways have been just written by the other two most recent answers :).
Also, even though it was not asked, but I got interested in performance, and I wanted to share the results of a rather simple benchmark:
Input
z = [('aaa',) for i in range(10000)]
@Paul Rooney
%timeit itertools.chain.from_iterable(z)
# 129 ns ± 2.52 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
@COLDSPEED
%timeit [x[0] for x in z]
# 254 µs ± 1.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
@this
%timeit list(zip(*z))[0]
# 272 µs ± 794 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
@mentalita
%timeit [str(*x) for x in z]
# 809 µs ± 904 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Use a simple list comprehension:
>>> my_list_of_tuples = [('GGG',), ('AAA',), ('BBB',)]
>>> my_list_of_strings = [str(*x) for x in my_list_of_tuples]
>>> my_list_of_strings
['GGG', 'AAA', 'BBB']
t=[('GGG',), ('AAA',), ('BBB',)]
str=[]
for each in t:
str.append(each[0])
print str
Above one gives list of strings
you can just use itertools
chain
method tested in python2
& python3
from itertools import chain
data = [('GGG',), ('AAA',), ('BBB',)]
for item in itertools.chain(*data):
print(item)
The itertools.chain method returns
chain
object, you can get elements usinglist
oriterate
usingfor
.
You can use 'isinstance
' or type()==tuple
method can done the job in just one line using list comprehension :
print([j for i in your_list for j in i if isinstance(i,tuple)])
:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.