简体   繁体   English

在子列表中查找包含元组的列表中的最小值

[英]Find the smallest value in a list with tuples inside a sublist

I need to find the smallest value in a list.我需要在列表中找到最小值。 The list has sublists which contains tuples.该列表具有包含元组的子列表。 I need to find the smallest value in all of those tuples, but it can only include the first 3 values.我需要在所有这些元组中找到最小值,但它只能包含前 3 个值。 I managed to achieve with the following code, but I want it to look cleaner.我设法用下面的代码实现了,但我希望它看起来更干净。

lst = [[(1, 2, 3, 50)], [(0.2, 0.4, 2, 0.1)], [(0.6, 0.8, 1.2, 0.05)]]

def FitScoreSearch3(fitscores):

  fitscores2 = []
  for x in fitscores:
      for y in x:
          for z in y[:3]:
              fitscores2.append(z)

  return min(fitscores2)

The output is 0.2 as it should be. output 应该是 0.2。 The output can't be 0.05. output 不能为 0.05。

Do your sublists always contain just a single tuple?你的子列表总是只包含一个元组吗? If so,如果是这样,

def FitScoreSearch3(fitscores):
    return min(min(x[0][:3]) for x in fitscores)

If the sublists are allowed to contain several tuples:如果允许子列表包含多个元组:

def FitScoreSearch3(fitscores):
    return min(min(y[:3]) for x in fitscores for y in x)

In both cases, this swaps your loops for generator expressions.在这两种情况下,这都会将您的循环替换为生成器表达式。 Also, instead of collecting all the numbers into one big list and then do the min() , the above compute the min() first on the tuple (or rather the first 3 elements of the tuple), after which the global minimum value is computed as the min() of all these "sub-min values".此外,不是将所有数字收集到一个大列表中然后执行min() ,而是首先在元组(或者更确切地说是元组的前 3 个元素)上计算min() ) ,之后全局最小值为计算为所有这些“亚最小值”的min() As this does not create an additional data structure, it's faster.由于这不会创建额外的数据结构,因此速度更快。

min([value for sublist in lst for value in sublist[0][:3]])

In this code lst2 contains all the values of the first 3 elements of each tuple.在此代码中, lst2 包含每个元组的前 3 个元素的所有值。

lst2 = [ x for sublist in lst for tpl in sublist for x in tpl[:3] ]
print(min(lst2)) # 0.2

You could do something like -你可以做类似的事情 -

def fitScoreSearch3(fitScores):
    lst = list(map(lambda x: list(x[0][:3]), fitScores))
    minimum = min(list(map(min, lst)))
    return minimum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM