我有一个列表列表,我不知道主列表的长度,但每个'子列表'必须包含6个浮点数.我需要比较每个子列表的每个浮点数,并保持较小的一个用于前三个浮点数,而较高的一个用于最后三个浮点数,最后,我需要以相同的顺序在6浮点列表中返回所有这些值.
这是一个例子:
list1 = [[-2.0, 0.0, -2.0, 2.0, 10.0, 2.0], [-1.0, 0.0, 2.0, 1.0, 5.0, 4.0]]
# Compare list1[0][0] with list1[1][0]
# Will return -2.0 (because the index is between 0 and 2 so it returns the lower float)
# Compare list1[0][4] with list1[1][4]
# Will return 10.0 (because the index is between 3 and 5 so it returns the higher float)
# The final result which should be returned is:
# [-2.0, 0.0, -2.0, 2.0, 10.0, 4.0]
list2 = [[-2.0, 0.0, -2.0, 2.0, 10.0, 2.0], [-1.0, 0.0, 2.0, 1.0, 5.0, 4.0], [3.0, 0.0, -1.0, 4.0, 1.0, 0.0]]
# Compare list2[0][2] with list2[1][2] with list2[2][2]
# Will return -2.0 (because the index is between 0 and 2 so it returns the lower float)
# The final result which should be returned is:
# [-2.0, 0.0, -2.0, 4.0, 10.0, 4.0]
Run Code Online (Sandbox Code Playgroud)
我zip()
在这个网站上阅读,设置,列表理解和不同的主题,但我无法实现我想要的.
如果这样做zip(*list2)
,您将一起创建每个子列表的第一个元素的列表,将第二个元素组合在一起,等等.因此,您希望获得前3个的最小值和下一个3的最大值.
zipped = zip(*list2)
result = [min(zipped[i]) for i in range(3)] + [max(zipped[i]) for i in range(3, 6)]
Run Code Online (Sandbox Code Playgroud)
在Python 3中,zip()
它将像迭代器一样懒惰地获取压缩的子列表,而在Python 2中它将提前创建整个列表.这类似于range()
两个版本之间.如果你想在Python 2中使用延迟生成,可以使用itertools模块中的迭代器版本.
import itertools
zipped = itertools.izip(*list2)
result = [min(zipped.next()) for _ in range(3)] + [max(zipped.next()) for _ in range(3)]
Run Code Online (Sandbox Code Playgroud)
编辑:zip()
实现目标的视觉示例.
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> zip(*a) # you need `list(zip(*a))` in Python 3
[(1, 4), (2, 5), (3, 6)]
Run Code Online (Sandbox Code Playgroud)
星形语法在几个参数中解压缩列表,因此zip(*[[1, 2, 3], [4, 5, 6]])
变为zip([1, 2, 3], [4, 5, 6])
,这就是你想要的.