草庐IT

python - 嵌套列表上的 min/max 函数如何工作?

coder 2023-05-24 原文

假设有一个嵌套列表,例如:

my_list = [[1, 2, 21], [1, 3], [1, 2]]

当函数 min() 被调用时:

min(my_list)

收到的输出是

[1, 2]

为什么以及它是如何工作的?它有哪些用例?

最佳答案

如何在 Python 中比较列表和其他序列?

比较 Python 中的列表(和其他序列)lexicographically而不是基于任何其他参数。

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.


什么是字典排序?

来自 lexicographic sorting 上的维基百科页面

lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters.

min 函数返回 iterable 中的最小值。所以[1,2]的字典值是该列表中最少的。您可以使用 [1,2,21] 进行检查

>>> my_list=[[1,2,21],[1,3],[1,2]]
>>> min(my_list)
[1, 2]

min 这种情况下发生了什么? ?

my_list 上的元素明智, 首先 [1,2,21][1,3] .现在来自文档

If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively.

因此 [1,1,21] 的值小于 [1,3] , 因为 [1,3] 的第二个元素,即 3 按字典顺序高于 [1,1,21] 的第二个元素的值,即 1 .

现在比较 [1,2][1,2,21] ,并从文档中添加另一个引用

If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.

[1,2][1,2,21] 的初始子序列.因此 [1,2] 的值整体小于[1,2,21] .因此[1,2]作为输出返回。

这可以通过使用 sorted 来验证。功能

>>> sorted(my_list)
[[1, 2], [1, 2, 21], [1, 3]]

如果列表有多个最小元素怎么办?

如果列表包含重复的最小元素返回第一个

>>> my_list=[[1,2],[1,2]]
>>> min(my_list)
[1, 2]

这可以通过 id 来确认。函数调用

>>> my_list=[[1,2],[1,2]]
>>> [id(i) for i in my_list]
[140297364849368, 140297364850160]
>>> id(min(my_list))
140297364849368

我需要做些什么来防止 min 中的字典比较?

如果所需的比较不是字典顺序,那么 key可以使用参数(如 Padraic 所述)

min函数有一个名为 key附加可选参数 . key参数接受一个函数。

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).

例如,如果我们需要长度最小的元素,我们需要使用 len 功能。

>>> my_list=[[1,2,21],[1,3],[1,2]]
>>> min(my_list,key=len)            # Notice the key argument
[1, 3]

我们可以看到这里返回了第一个最短的元素。


如果列表是异构的怎么办?

直到 Python2

如果列表是异类的类型名称考虑排序,检查Comparisions ,

Objects of different types except numbers are ordered by their type names

因此,如果您输入 intlist在那里你会得到最小的整数值i低于 l .同样'1'将比这两者都具有更高的值(value)。

>>> my_list=[[1,1,21],1,'1']
>>> min(my_list)
1

Python3 及更高版本

但是,Python3 中删除了这种令人困惑的技术。它现在引发了 TypeError 。阅读 What's new in Python 3.0

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other.

>>> my_list=[[1,1,21],1,'1']
>>> min(my_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < list()

但它适用于可比较的类型,例如

>>> my_list=[1,2.0]
>>> min(my_list)
1

在这里我们可以看到 list包含 float值和 int值(value)观。但是作为 floatint是可比较的类型,min函数在这种情况下有效。

关于python - 嵌套列表上的 min/max 函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050113/

有关python - 嵌套列表上的 min/max 函数如何工作?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  7. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

随机推荐