我正在尝试对格式
的元组列表进行排序[(0.001,"hello"), (0.005,"world"),(0.004,"sort"), (0.002,"me")]
这应该给出输出:
[(0.001, "hello"), (0.002,"me"), (0.004, "sort"), (0.005, "world")]
目前我正在使用方法
sorted(my_list , key=lambda x: x[0])
但这会产生错误:
TypeError: 'float' object is not subscriptable
这是什么原因,我该如何解决?
我使用的是Python 3.6.1版
非常感谢
答案 0 :(得分:1)
您可以my_list = sorted(my_list)
来利用sorted()
的自然排序机制。
另外,我没有收到您所犯的错误,我猜这是因为您在调用list
)时使用了保留字sorted(list, key=...
。尝试将其命名为其他内容。
这是一个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')]