在lis中增加列表(但不包括其他可扩展列表)

2024-10-04 15:20:52 发布

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

我有一个数据结构:

a = ['test', 32, ('tuple', 'example'), ['a', 'b', 2], ['c', 'd', 3]]

我想要:

^{pr2}$

我试过了:

c = [a[0], a[1], a[2], [l for l in a[3]], [j for j in a[4]]]

结果是c匹配a。我还试过:

c = [a[0], a[1], a[2], ''.join(str(l) for l in a[3]), ''.join(str(j) for j in a[4])]
> c
['test', 32, ('tuple', 'example'), 'ab2', 'cd3']

这会导致join使所有内容都成为字符串。把我的列表变成3个项目的join在哪里?似乎唯一的方法是指定子列表的每个索引,这在我看来是愚蠢的

c = [a[0], a[1], a[2], a[3][0], a[3][1], a[3][2], a[4][0], a[4][1], a[4][2]]
> c
['test', 32, ('tuple', 'example'), 'a', 'b', 2, 'c', 'd', 3]

如何最好地得到我想要的输出?在


Tags: 项目字符串intest数据结构内容列表for
3条回答

理解是你的朋友:

[i for e in a for i in (e if isinstance(e, list) else [e])]

演示:

^{pr2}$

更新

在这个理解中,我们应该单独读两个fors:

^{3}$

这个理解包含两层for。第一个循环遍历原始列表a,并提取出每个元素并调用它们e。在

因为您需要的是展平所有list,所以我们需要另一个层来进行展平,这是第二层。因为if-else部分处理两个场景:一个用于列表案例,另一个用于其他案例。当它是一个列表时,您希望遍历它的内容,而对于其余部分,您希望保持这样的状态,所以最简单的方法就是将元素包装在list内,以创建一个单例。然后我们只需要逐个返回这个已处理列表中的任何内容,在本例中是i。在

最具可读性的方法可能是一个简单的for循环,它扩展列表项并将非列表项附加到新列表:

a = ['test', 32, ('tuple', 'example'), ['a', 'b', 2], ['c', 'd', 3]]
ans = []
for item in a:
     ans.extend(item) if isinstance(item,list) else ans.append(item)
# ans: ['test', 32, ('tuple', 'example'), 'a', 'b', 2, 'c', 'd', 3]

您可以使用此选项对a中的每种类型进行排序:

a = ['a',('tuple','example'),['b','c','d'],5]
newa = []
for x in a:
    if type(x) is list:
        for y in x:
            newa.append(y)
    else:
        newa.append(x)

print(newa)

效率不是很高,但是嘿,这很管用。在

编辑: 你也可以使用这个:

^{pr2}$

相关问题 更多 >

    热门问题