find min values by each element index in a list of objects

时间:2019-04-08 13:54:33

标签: python

I have this object instances below which has pid and pos list which the elements can range from 3-10, I will use three elements for now.

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)

which results:

[6, 1, 10]
[9, 1, 7]
[12, 1, 4]

I need a way to get min values of those three by each index and make list comprehension such that the expected output should be:

[6, 1, 4]

What I have tried out so far:

I have tried this way which is actually not good approach, because it will work only if the list objects and the 'pos' list elements are three only.

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]

Another approach which only works if the list is not object instances... but it isn't the way I want.

lst3 = [[6, 1, 10], [9, 1, 7], [12, 1, 4]]  

lst3 = list(map(min, *lst3))
print(lst3)
>> [6, 1, 4]

So how to do it?

4 个答案:

答案 0 :(得分:4)

您可以这样做:

lst[]
n = 5
for index in range(n):        
    lst.append(Ppl(index))

result = list(map(min, *[x.pos for x in lst]))

答案 1 :(得分:2)

这是一种处理现有显示列表的方法,其中每个列表可以具有任意长度,只要所有内部列表的长度相同:

from functools import reduce

data =  [[6, 1, 10],
        [9, 1, 7],
        [12, 1, 4]]

mins = []

len = len(data[0])
for i in range(len):
    mins.append(reduce((lambda x, y: [min(x[i], y[i])] * len), data)[0])

print mins

结果:

[6, 1, 4]

答案 2 :(得分:2)

您只能在该类的第一个实例的数组中找到元素的数量(每个实例在其positions数组中必须具有相同数量的元素)

lst2 = []

numOfObjects = len(lst) #number of instances of the class 'Ppl'

numElements = len(lst[0].pos) #number of elements in array of EACH class instance

for index in range(numElements):

    rst = min([lst[i].pos[index] for i in range(numOfObjects)])
    lst2.append(rst)

print (lst2)

答案 3 :(得分:1)

您可以使用以下代码

import  numpy as np

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))
a=[]
for index in range(len(lst)):
    # print(lst[index].pos)
    a.append(lst[index].pos)

print(np.min(a,axis=0))