我想将列表转换为列表,并且在这些列表中,列表仅转换为列表。例如:
我的代码:
a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
aaa = len(a)
aa = [[] for i in range(aaa)]
for i, x in enumerate(a):
if len(x) != 0:
for xx in x:
for xxx in xx:
aa[i].append(xxx)
print(aa)
当前:
a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
符合预期:
[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
我当前的代码可用于查找预期的输出。但是,我必须使用太多的for循环及其太深的内容。有没有像一两行这样的更短方法呢?
答案 0 :(得分:1)
您可以通过列表理解来做到这一点,只需检查嵌套列表是否为空,如果不是,则将内部列表替换为内部列表(按索引)。
data = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
result = [d[0] if d else d for d in data]
print(result)
# OUTPUT
# [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
答案 1 :(得分:1)
我为此使用了itertools。了解更多信息flatten list of list in python
import itertools
a=[[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
a = [list(itertools.chain(*li)) for li in a]
print(a)
输出
[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
答案 2 :(得分:1)
尝试next
和iter
:
a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
print([next(iter(i),[]) for i in a])
输出:
[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
答案 3 :(得分:1)
这里似乎解决了所有短方法,是对大多数这些过程中正在发生的事情的扩展解释。您几乎是unpacking
的嵌套列表,并且没有碰到空列表。
a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
result = []
for i in a:
if i == []:
result.append(i)
else:
result.append(*i)
print(result)
# [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]
答案 4 :(得分:0)
由于您要展平内部子列表,因此可以在列表推导中使用列表推导:
[[i for s in l for i in s] for l in a]
这将返回:
[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]