使用排序后的内建函数对python字典的值进行排序(sorting values of python dict using sorted builtin function)
我需要得到一个字典的排序表示,按照值的降序排列(首先显示字典中的最大值)。
样品:
mydict={u'jon':30,u'den':26,u'rob':42,u'jaime':31}
我需要向他们展示
rob=42 jaime=31 jon=30 den=28
我试过这个
from operator import itemgetter sortedvalues=sorted(mydict,key=itemgetter(1))
当我打印我得到的列表
[u'jaime', u'den', u'rob', u'jon']
这个清单是无序的! 我是否错过了有关内置排序的用法? 还是我不正确地使用itemgetter?
I need to get a sorted representation of a dict ,sorted in the descending order of values (largest value in dict to be shown first).
sample:
mydict={u'jon':30,u'den':26,u'rob':42,u'jaime':31}
I need to show them like
rob=42 jaime=31 jon=30 den=28
I tried this
from operator import itemgetter sortedvalues=sorted(mydict,key=itemgetter(1))
When I print the list I get
[u'jaime', u'den', u'rob', u'jon']
This list is unordered! Am I missing something about the usage of sorted builtin ? or am I using the itemgetter incorrectly?
原文:https://stackoverflow.com/questions/9849192
最满意答案
你已经调用了
makeCounter()
一次。 这将创建您的新关闭,并将其分配给counter1
。 这个闭包关闭在可变变量上,并且只要闭包存在就会保持捕获。调用
counter1()
将执行它,但它保留相同的捕获n
,并对其进行变异。 这个特殊的“加法器”总是会捕获这个相同的n
,只要它存在..为了获得你所建议的行为,你需要制作新的关闭来捕获
n
新实例:let counter1 = makeCounter() counter1() // returns 1 counter1() // returns 2 counter1() // returns 3 var counter2 = makeCounter() counter2() // returns 1 counter2 = makeCounter() counter2() // returns 1 counter2 = makeCounter() counter2() // returns 1
现在
counter1
和counter2
都有自己独立的n
实例。You've called
makeCounter()
once. That creates your new closure, and assigns it tocounter1
. This closure closes over the mutablevar n
, and will remain captured as long as this closure exists.Calling
counter1()
will execute it, but it retains the same capturedn
, and mutates it. This particular "adder" will ALWAYS capture this samen
, so long as it exists..To get the behavior you're suggesting, you need to make new closures which capture new instances of
n
:let counter1 = makeCounter() counter1() // returns 1 counter1() // returns 2 counter1() // returns 3 var counter2 = makeCounter() counter2() // returns 1 counter2 = makeCounter() counter2() // returns 1 counter2 = makeCounter() counter2() // returns 1
Now both
counter1
andcounter2
each have their own separate instances ofn
.
相关问答
更多-
你已经调用了makeCounter()一次。 这将创建您的新关闭,并将其分配给counter1 。 这个闭包关闭在可变变量上,并且只要闭包存在就会保持捕获。 调用counter1()将执行它,但它保留相同的捕获n ,并对其进行变异。 这个特殊的“加法器”总是会捕获这个相同的n ,只要它存在.. 为了获得你所建议的行为,你需要制作新的关闭来捕获n新实例: let counter1 = makeCounter() counter1() // returns 1 counter1() // returns 2 ...
-
首先:请确保将来提供MCVE ,在能够重现问题之前修复语法错误并不好玩: http : //is.gd/tXr7WK Rust不知道第二个闭包可以运行的唯一方法是,如果第一个闭包没有运行并且永远不会运行。 您可以等待let/else RFC被接受,实现和稳定,或者您可以按步骤创建错误,首先创建一个内部闭包,为该错误类型执行所有操作而不token ,然后运行闭包,然后将错误映射到您的自定义错误类型。 || -> _ { try!(do_stuff("a").map_err(|e| ("foo".to_ ...
-
是的,这是预期的行为(编辑:......它实际上是一个古老的已知错误! https: //issues.dlang.org/show_bug.cgi?id = 2043所以只能预料到它会发生并且你很容易被使用对它,但它实际上不应该发生)并且在其他语言中也可以看到,所以这是一个很好的原则。 要在循环中获取变量的单独副本,请调用另一个返回要存储的委托的函数,并将循环变量传递给它。 import std.stdio; alias Clojure = void delegate(); Clojure[] cloju ...
-
你的第二个问题已经回答了,但是对于你的第一个问题: 关闭捕获是什么? Python中的范围是 动态和 词汇。 闭包将始终记住变量的名称和范围,而不是其指向的对象。 由于示例中的所有函数都在相同的范围内创建,并使用相同的变量名称,所以它们总是引用相同的变量。 编辑:关于你如何克服这个问题的其他问题,有两种方法可以想到: Adrien Plisson推荐的最简洁但不是严格的等效方式。 创建一个带有额外参数的lambda,并将额外的参数的默认值设置为要保留的对象。 每次创建一个lambda时,都会创建一个新的范围 ...
-
你为什么要那样做? 也许这会更简单: // simple class with private member var Car = function(options) { var settings = $.extend({ noOfWheels: 2 }, options || {}); // Public method - can be called from client code this.honk = function(){ alert(setting ...
-
大卫的回答是完全正确的,但我认为我会举一个例子说明捕获实际上是如何工作的: func captureMe() -> (String) -> () { // v~~~ This will get 'captured' by the closure that is returned: var capturedString = "captured" return { // The closure that is returned will print the old ...
-
不需要anotherFunctionWithTrailingClosure的[weak self] 。 你可以凭经验测试一下: class Experiment { func someFunctionWithTrailingClosure(closure: () -> ()) { print("starting someFunctionWithTrailingClosure") dispatch_after(dispatch_time(DISPATCH_TIME_N ...
-
闭包如何捕获值?(How does the closure capture values?)[2023-05-16]
您应该查看文档 ,但这是一个示例排序函数(选择排序,因为这是最简单的): func selectionSort(inout array: [T], comparator: (T,T) -> Bool) { var min: Int for n in 0.. 避免闭包中的转义值(Avoiding escaped values in closures)[2021-10-15]
你可以这样做: for(int i=0; i<10; i++) { int number = i; MyApi.AddLazyCreate(() => new foo(/*other params*/ number)); } 这将导致它在循环的每次迭代中捕获不同的数字。 You can just do this: for(int i=0; i<10; i++) { int number = i; MyApi.AddLazyCreate(() => new foo(/*ot ...捕获嵌套闭包中的值(Capturing values in nested closures)[2022-03-21]
错误消息具有误导性。 你的代码几乎是正确的,“唯一”的问题是crc32()的最后一个参数,它需要是一个uInt : func calculateCrc32(_ crc: UInt, value: inout T) -> UInt { let size = MemoryLayout.size(ofValue: value) let result = withUnsafePointer(to: &value, { $0.withMemoryRebound(to: Bytef ... 相关文章
更多- Python内建函数(G)
- Python内建函数(D)
- Python内建函数(F)
- python字典操作
- Python内建函数(B)
- Python内建函数(H)
- Python内建函数(E)
- Python内建函数(A)
- Python内建函数(C)
- python2和python3的区别
最新问答
更多- 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
- 如何通过引用返回对象?(How is returning an object by reference possible?)
- 矩阵如何存储在内存中?(How are matrices stored in memory?)
- 每个请求的Java新会话?(Java New Session For Each Request?)
- css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
- 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
- xcode语法颜色编码解释?(xcode syntax color coding explained?)
- 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
- 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
- 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
- 西安哪有PLC可控制编程的培训
- 在Entity Framework中选择基类(Select base class in Entity Framework)
- 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
- 电脑二级VF有什么用
- Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
- 金华英语角.
- 手机软件如何制作
- 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
- 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
- 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
- Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
- 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
- python的访问器方法有哪些
- DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
- 在Ruby中对组合进行排序(Sorting a combination in Ruby)
- 网站开发的流程?
- 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
- 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
- 透明度错误IE11(Transparency bug IE11)
- linux的基本操作命令。。。