我有一份清单清单,我不知道主要清单的长度,但是每个子清单都是'必须包含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]
我在本网站上阅读了zip()
,集合,列表理解和不同主题,但我无法实现我的目标。
答案 0 :(得分:6)
如果你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)]
在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)]
修改:zip()
取得的成就的可视示例。
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> zip(*a) # you need `list(zip(*a))` in Python 3
[(1, 4), (2, 5), (3, 6)]
星形语法在多个参数中解压缩列表,以便zip(*[[1, 2, 3], [4, 5, 6]])
变为zip([1, 2, 3], [4, 5, 6])
,这就是您想要的。
答案 1 :(得分:1)
您可以手动执行此操作"使用2个嵌套for循环
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]]
output = [0 for x in range(6)]
# iterate over the 6 numbers
for i in range(6):
value = list1[0][i] # pick the first number
#iterate over all the lists, if we find a bigger/smaller one our current one then save it
for j in range(len(list1)):
if i >= 3 and list1[j][i] > value:
value = list1[j][i]
elif i < 3 and list1[j][i] < value:
value = list1[j][i]
#put the biggest/smallest value in the correct place in the output array
output[i] = value
print output
答案 2 :(得分:0)
您可以使用NumPy:
np.concatenate((np.min(a[:,:3], axis=0), np.max(a[:,3:], axis=0)))
import numpy as np
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]]
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]]
a1 = np.array(list1)
a2 = np.array(list2)
for a in [a1, a2]:
print(list(np.concatenate((np.min(a[:,:3], axis=0), np.max(a[:,3:], axis=0)))))
打印:
[-2.0, 0.0, -2.0, 2.0, 10.0, 4.0]
[-2.0, 0.0, -2.0, 4.0, 10.0, 4.0]