简体   繁体   English

Python:列表中的最小数字

[英]Python: smallest number in list

I'm new to python and i don't know how to find the smallest number in each array.我是 python 的新手,我不知道如何在每个数组中找到最小的数字。 The input is [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ] and the output should be [2, 3, 5, 1] .输入是[ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]并且 output 应该是[2, 3, 5, 1] I have try this:我试过这个:

x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
minimal = x[0]
  for i in range(len(x)):
      if (x[i]< minimal):
          minimal = x[i]
print(minimal)

And the output that i got is [2] , i have no idea about this.而我得到的 output 是[2] ,我对此一无所知。 Please help me...请帮我...

We can simply iterate through the nested list and append the minimum values for each of the list item.我们可以简单地遍历嵌套列表和 append 每个列表项的最小值。

smallest = []
for listItem in x:
    smallest.append(min(listItem))

Now, smallest list should be the expected output list.现在, smallest的列表应该是预期的 output 列表。

First, we need to get individual lists from list x using for lst in x: .首先,我们需要使用for lst in x:从列表x中获取单个列表。 Then we find the minimum value of that list using min() function & append it to your minimal list using minimal.append(min(lst)) , then print the final minimal list Now you will have your output as [2, 3, 5, 1]然后我们使用min() function & append 找到该列表的最小值,使用 minimum.append minimal.append(min(lst))将其添加到您的minimal列表中,然后打印最终minimal list现在您将拥有您的[2, 3, 5, 1]

Now try & understand this code:现在尝试理解这段代码:

x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]

minimal = []

for lst in x:
    minimal.append(min(lst))
print(minimal)

try this:尝试这个:

list(map(lambda x:min(x),[[2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]))

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

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