![](/img/trans.png)
[英]How to get TouchSensor nested under joint in Webots (Python API)
[英]Joint nested list in Python
如何转换如下的嵌套列表?
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
-> [['a','b','c'], ['d','e','f']]
我发现了类似的问题。 但这有点不同。 在python中加入列表列表
我的不聪明
new = []
for elm in d:
tmp = []
for e in elm:
for ee in e:
tmp.append(ee)
new.append(tmp)
print(new)
[['a', 'b', 'c'], ['d', 'e', 'f']]
有很多方法可以做到这一点,但是一种方法是使用链
from itertools import chain
[list(chain(*x)) for x in d]
结果是:
[['a', 'b', 'c'], ['d', 'e', 'f']]
sum(ls, [])
使列表变平是有问题的,但是对于简短列表,它太简洁了,不予提及
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
[sum(ls, []) for ls in d]
Out[14]: [['a', 'b', 'c'], ['d', 'e', 'f']]
这是您问题的简单解决方案
new_d = []
for inner in d:
new_d.append([item for x in inner for item in x])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.