![](/img/trans.png)
[英]TypeError: 'float' object is not subscriptable when iterating through list of tuples and examining the first str from each tuple
[英]Sorting list of tuples by first element that is a float: TypeError: 'float' object is not subscriptable
我正在尝试对格式的元组列表进行排序
[(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版
非常感谢
您可以执行my_list = sorted(my_list)
来利用sorted()
的自然排序机制。
另外,我没有得到您所做的错误,我猜是因为您在对sorted(list, key=...
)`的调用中使用了保留字list
。 尝试命名其他名称。
这是一个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.