[英]Sorting list of tuples by first element that is a float: TypeError: 'float' object is not subscriptable
I am trying to sort a list of tuples of the format 我正在尝试对格式的元组列表进行排序
[(0.001,"hello"), (0.005,"world"),(0.004,"sort"), (0.002,"me")]
This should give the output: 这应该给出输出:
[(0.001, "hello"), (0.002,"me"), (0.004, "sort"), (0.005, "world")]
Currently I am using the method 目前我正在使用该方法
sorted(my_list , key=lambda x: x[0])
This however gives the error: 但是,这给出了错误:
TypeError: 'float' object is not subscriptable
What is the reason for this, and how can I fix it? 这是什么原因,我该如何解决?
I am using Python version 3.6.1 我正在使用Python 3.6.1版
Many thanks 非常感谢
You can just do my_list = sorted(my_list)
to take advantage of the natural sorting mechanics of sorted()
. 您可以执行my_list = sorted(my_list)
来利用sorted()
的自然排序机制。
Also, I don't get the error you do, and I'm guessing it's because you use the reserved word list
in your call to sorted(list, key=...
)`. 另外,我没有得到您所做的错误,我猜是因为您在对sorted(list, key=...
)`的调用中使用了保留字list
。 Try naming it something else. 尝试命名其他名称。
Here's an iPython repl session: 这是一个iPython repl会话:
Jupyter console 5.1.0
Python 3.6.0 (default, Dec 24 2016, 08:01:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.2.2 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: x = [(0.001,"hello"), (0.005,"world"),(0.004,"sort"), (0.002,"me")]
In [2]: sorted(x)
Out[2]: [(0.001, 'hello'), (0.002, 'me'), (0.004, 'sort'), (0.005, 'world')]
In [3]: sorted(x, key=lambda x: x[0])
Out[3]: [(0.001, 'hello'), (0.002, 'me'), (0.004, 'sort'), (0.005, 'world')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.