我有一个数据结构:
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]
如何最好地得到我想要的输出?在
理解是你的朋友:
演示:
^{pr2}$更新
在这个理解中,我们应该单独读两个fors:
^{3}$这个理解包含两层for。第一个循环遍历原始列表
a
,并提取出每个元素并调用它们e
。在因为您需要的是展平所有
list
,所以我们需要另一个层来进行展平,这是第二层。因为if-else部分处理两个场景:一个用于列表案例,另一个用于其他案例。当它是一个列表时,您希望遍历它的内容,而对于其余部分,您希望保持这样的状态,所以最简单的方法就是将元素包装在list
内,以创建一个单例。然后我们只需要逐个返回这个已处理列表中的任何内容,在本例中是i
。在最具可读性的方法可能是一个简单的
for
循环,它扩展列表项并将非列表项附加到新列表:您可以使用此选项对a中的每种类型进行排序:
效率不是很高,但是嘿,这很管用。在
编辑: 你也可以使用这个:
^{pr2}$相关问题 更多 >
编程相关推荐