Python将一个变量内的多个列表合并为一个lis

2024-06-07 04:35:57 发布

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

我很难将多个列表放入一个变量中,因为它们都在一个变量中。在

以下是一个例子:

我拥有的

a = ['1'], ['3'], ['3']

我想要什么

^{pr2}$

如何使用python3.x解决这个问题


编辑

这是我正在研究的代码。在

from itertools import chain

def compteur_voyelle(str):
    list_string = "aeoui"
    oldstr = str.lower()
    text = oldstr.replace(" ", "")
    print(text)

    for l in list_string:
        total = text.count(l).__str__()
        answer = list(chain(*total))
        print(answer)

compteur_voyelle("Saitama is the One Punch Man.")

控制台结果:

saitamaistheonepunchman.
['4']
['2']
['1']
['1']
['2']

Tags: textanswerchain列表stringpython3list例子
3条回答

按照与其他答案相同的例子,我想也可以使用内置的sum来实现这一点:

In [1]: a = [1], [3], [3]

In [2]: sum(a, [])
Out[2]: [1, 3, 3]
a = ['1'], ['3'], ['3']

>>> type(a)
<class 'tuple'> 

这里是元组。我们可以把列表转换成元组。在

^{pr2}$

您可以使用itertools.chain。在

In [35]: from itertools import chain

In [36]: a = ['1'], ['3'], ['3']

In [37]: list(chain(*a))
Out[37]: ['1', '3', '3']

或者

^{pr2}$

相关问题 更多 >