将元组列表转换为字符串列表

2024-04-25 06:12:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个元组列表,例如[('GGG',), ('AAA',), ('BBB',)],我想把它转换成一个字符串列表:['GGG' , 'AAA', 'BBB']。你知道吗

我曾尝试将for循环与join方法一起使用,但无法使其工作。任何帮助都将不胜感激,谢谢。你知道吗


Tags: 方法字符串列表for元组joinbbbaaa
3条回答

使用简单的列表理解:

>>> 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']

^{}使用^{}

例如

from itertools import chain
x = [('GGG',), ('AAA',), ('BBB',)]
print(list(chain.from_iterable(x)))

输出

['GGG', 'AAA', 'BBB']

使用list只允许打印输出。它强制立即计算从chain.from_iterable返回的惰性对象。如果以后要在对象上迭代,则不需要它。你知道吗

有多种方法可以实现这一点。如果数组是z = [('GGG',), ('AAA',), ('BBB',)],则:

1)使用ziplist(list(zip(*z))[0])

其他的方法都是由另外两个最新的答案写成的:)。你知道吗

另外,虽然没有人问我,但我对性能很感兴趣,我想分享一个相当简单的基准测试的结果:

输入

z = [('aaa',) for i in range(10000)]

@保罗·鲁尼

%timeit itertools.chain.from_iterable(z)
# 129 ns ± 2.52 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

@冷速

%timeit [x[0] for x in z]
# 254 µs ± 1.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

@这个

%timeit list(zip(*z))[0]
# 272 µs ± 794 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

@精神塔

%timeit [str(*x) for x in z]
# 809 µs ± 904 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

相关问题 更多 >