我下面有这个对象实例,它有 pid 和 pos 列表,元素范围为 3-10,我现在将使用三个元素。
lst = []
class Ppl:
def __init__(self, pid):
# local variables
self.pid = pid
self.pos = [3*pid+6, 1, 10+pid-4*pid]
for index in range(3):
lst.append(Ppl(index))
for index in range(len(lst)):
print(lst[index].pos)
结果:
[6, 1, 10]
[9, 1, 7]
[12, 1, 4]
我需要一种方法来通过每个索引获取这三个的最小值并进行列表理解,以便预期输出应该是:
[6, 1, 4]
到目前为止我已经尝试过:
我已经尝试过这种方法,但实际上这不是一个好方法,因为它只有在列表对象和'pos'列表元素只有三个时才有效。
lst2 = []
for index in range(len(lst)):
rst = min(lst[0].pos[index],lst[1].pos[index],lst[2].pos[index])
lst2.append(rst)
print(lst2)
>> [6, 1, 4]
另一种方法仅在列表不是对象实例时才有效...但这不是我想要的方式。
lst3 = [[6, 1, 10], [9, 1, 7], [12, 1, 4]]
lst3 = list(map(min, *lst3))
print(lst3)
>> [6, 1, 4]
那么怎么做呢?
最佳答案
你可以这样做:
lst[]
n = 5
for index in range(n):
lst.append(Ppl(index))
result = list(map(min, *[x.pos for x in lst]))
关于python - 通过对象列表中的每个元素索引查找最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55575097/