我想在python中使用三元组列表理解来创建一个平面列表。
mynested = [[['1229'], [['2020-11'], ['2020-1'], ['2020']]], [['1230'], [['2020-12'],['2020-2'], ['2020']]]]我希望它像这样工作。
short=[]
for a in mynested:
for b in a:
for c in b:
short.append(''.join(c))
for shrt in short:
print(shrt)结果:
1229
2020-11
2020-1
2020
1230
2020-12
2020-2
2020但是我如何通过列表理解来获得这个结果呢?
发布于 2021-07-12 02:35:56
我不知道你说得到“print”的“输出”是什么意思,但是用一个三重嵌套的列表做你想做的事情与一个双嵌套的列表非常相似。
所以怎么样-
output = [''.join(x) for z in mynested for y in z for x in y]你现在可以做-
for x in output:
print(x)
# 1229
# 2020-11
# 2020-1
# 2020
# 1230
# 2020-12
# 2020-2
# 2020发布于 2021-07-12 02:37:31
更新:你可以试试这个,它会给出你想要的输出:
print(*[''.join(c) for a in mynested for b in a for c in b], sep='\n')您不能在列表理解中创建打印函数,因为这将不返回值。例如下面的示例:
numbers = [1,2,3]
[print(x) for x in numbers]输出将是列表中的数字以及三个None值的列表。
https://stackoverflow.com/questions/68339009
复制相似问题