【发布时间】:2020-12-11 19:44:18
【问题描述】:
我正在尝试从三种列表中创建一个数组。比如l1、l2、l3。我收到错误说 float 不可迭代。如何在 python 中将这些列表解压成一维列表?
l1=[(260.3, 185.0), (268.01, 499.16)]
l2=[(268.01, 500.87), (678.9, 506.0)]
l3=((149.86, 354.48), (182.39, 344.2))
def unpack_lines(l1, l2, l3):
out = []
out.extend(l1[0][0])
out.extend(l1[0][1])
out.extend(l1[1][0])
out.extend(l1[1][1])
out.extend(l2[0][0])
out.extend(l2[0][1])
out.extend(l2[1][0])
out.extend(l2[1][1])
out.extend(l3[0][0])
out.extend(l3[0][1])
out.extend(l3[1][0])
out.extend(l3[1][1])
return out
unpack_lines(l1, l2, l3)
错误
TypeError Traceback (most recent call last)
<ipython-input-27-6f84bf5b956a> in <module>
----> 1 unpack_lines(l1, l2, l3)
<ipython-input-26-159b13d00464> in unpack_lines(l1, l2, l3)
1 def unpack_lines(l1, l2, l3):
2 out = []
----> 3 out.extend(l1[0][0])
4 out.extend(l1[0][1])
5 out.extend(l1[1][0])
TypeError: 'float' object is not iterable
预期输出
[260.3,
185.0,
268.01,
499.16,
268.01,
500.87,
678.9,
506.0,
149.86,
354.48,
182.39,
344.2]
【问题讨论】:
-
return list(itertools.chain.from_iterable(itertools.chain(l1, l2, l3))) -
extend接受一个可迭代的。你的意思可能是append,或者extend(list[i]) -
我想要 numpy 的一维数组,所以我确实扩展了 - 我正在尝试这样的事情 -
[a, b, c, d, e, f, ..... ] -
@wjandrea - 不是真的,他们只有列表,但在我的问题中,我有列表和元组。类似问题,谢谢
标签: python python-3.x list flatten