Python 通过对象列表中的每个元素索引查找除零以外的最小值
我在下面有一个函数,它将对象实例作为列表Python 通过对象列表中的每个元素索引查找除零以外的最小值,python,Python,我在下面有一个函数,它将对象实例作为列表 lst = [] class Ppl: def __init__(self, pid): # local variables self.pid = pid self.pos = [3*pid, 10+pid-4*pid, 5*pid] for index in range(3): lst.append(Ppl(index)) for index in range(le
lst = []
class Ppl:
def __init__(self, pid):
# local variables
self.pid = pid
self.pos = [3*pid, 10+pid-4*pid, 5*pid]
for index in range(3):
lst.append(Ppl(index))
for index in range(len(lst)):
print(lst[index].pos)
以上将输出
[0, 10, 0]
[3, 7, 5]
[6, 4, 10]
现在我想根据上面的列表制作一个理解列表,以获得除零以外的最小值。。因此,预期输出为
[3, 4, 5]
我在下面有这个函数,它可以工作,但它包含0
lst2 = list(map(min, *[x.pos for x in lst]))
print(lst2)
>> [0, 4, 0]
那么,是否有改进上述代码的方法或更好的解决方案?您可以轻松地为此定义一个函数:
def min2(iterator, threshold = 0):
minvalue = None
for x in iterator:
if (x > threshold) and (x < minvalue or minvalue is None):
minvalue = x
return minvalue
请尝试下面的代码片段
import numpy as np
lst2 = np.array([x.pos for x in lst])
lst2[lst2==0]=np.max(lst2)
print(np.min(lst2,axis=0))
输出:
[3 4 5]如果您被限制使用一个衬里,以下是可能的解决方案:
lst2 = list(map(lambda *args: min(arg for arg in args if arg != 0), *[x.pos for x in lst]))
min
替换为一个lambda,在过滤零值后应用min
。这不是一个坏方法,但我被限制使用一行/内联函数。我不太符合您的要求。当你说“正是我想要的”时,这似乎与你的描述不符,因为3
是零以上的最小元素,但它不包含在你的输出中。您是否在所有列表中选择了3个最小元素?我这样问是因为我注意到Ppl[0]
在列表中没有数字。ggorlen,我的意思是它可以工作,因为我想要的唯一问题是它包含0。
lst2 = list(map(lambda *args: min(arg for arg in args if arg != 0), *[x.pos for x in lst]))