python 获取数组中最小的数字

发布于 2024-10-21 16:16:52 字数 248 浏览 6 评论 0原文

我正在尝试用 python 编程

我有一个数组,其中包含

[A,20,False] [B,1,False] [C, 8, False]

等数据我希望能够通过获取元素来循环遍历数组具有最低的中间数字,因此例如要处理的下一个元素将是 B,因为它具有最小的数字 1。然后这个被删除,所以下一个要使用的元素将是 C,因为 20 和 8 中的 8 是最小的数字...

希望我说清楚了

请帮助

谢谢

I am trying to program in python

I have an array which holds data like

[A,20,False] [B,1,False] [C, 8, False]

I want to be able to loop through the array by getting the element with the lowest middle number so e.g. the next element to be worked on would be B because it has the smallest number one. Then this gets deleted so then the next element to be used would be C because out of 20 and 8 8 is the smallest number...

hope ive made this clear

Please help

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

久伴你 2024-10-28 16:16:52
>>> myList = [["A", 20, False], ["B", 1, False], ["C", 8, False]]
>>> smallest = min(myList, key=lambda L: L[1])
>>> smallest
['B', 1, False]

如果您想使用该元素对其进行排序,您可以使用 sorted 执行相同的操作:

>>> sorted(myList, key=lambda L: L[1])
[['B', 1, False], ['C', 8, False], ['A', 20, False]]
>>> myList = [["A", 20, False], ["B", 1, False], ["C", 8, False]]
>>> smallest = min(myList, key=lambda L: L[1])
>>> smallest
['B', 1, False]

If you'd like to sort it using that element you can do the same thing with sorted:

>>> sorted(myList, key=lambda L: L[1])
[['B', 1, False], ['C', 8, False], ['A', 20, False]]
怕倦 2024-10-28 16:16:52

这将为您提供编号最小的项目:

from operator import itemgetter

next = min(array,key=itemgetter(1))[0]

您还可以使用第二个项目作为键对列表进行排序:

array.sort(array,key=itemgetter(1))

This will give you the item with the smallest number:

from operator import itemgetter

next = min(array,key=itemgetter(1))[0]

You can also sort the list using the second item as the key:

array.sort(array,key=itemgetter(1))
渡你暖光 2024-10-28 16:16:52

首先对列表进行排序,然后按照您所说的方式循环遍历:

somelist = [[A,20,False] [B,1,False] [C, 8, False]]
somelist.sort(lambda x, y: cmp(x[1], y[1]))

for smallest in somelist:
    # do stuff with the smallest member

First sort the list and then loop through it as you said:

somelist = [[A,20,False] [B,1,False] [C, 8, False]]
somelist.sort(lambda x, y: cmp(x[1], y[1]))

for smallest in somelist:
    # do stuff with the smallest member
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文