Python dict_items 对象没有属性“排序”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28039155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:39:54  来源:igfitidea点击:

dict_items object has no attribute 'sort'

pythonreportlabptvs

提问by user960567

First of all I am new to Python. I am using PTVS http://pytools.codeplex.com/. Next I installed reportlab. Then I run a sample demo at https://github.com/nakagami/reportlab/blob/master/demos/colors/colortest.py#L68But at line,

首先,我是 Python 的新手。我正在使用 PTVS http://pytools.codeplex.com/。接下来我安装了reportlab。然后我在https://github.com/nakagami/reportlab/blob/master/demos/colors/colortest.py#L68 上运行一个示例演示但是在线,

all_colors = reportlab.lib.colors.getAllNamedColors().items()
all_colors.sort() # alpha order by name

I am getting error, dict_items object has no attribute sort

我收到错误, dict_items object has no attribute sort

采纳答案by Johan

Haven't tested but a theory: you are using python3!

还没有测试,但一个理论:你正在使用python3!

From https://docs.python.org/3/whatsnew/3.0.html

来自https://docs.python.org/3/whatsnew/3.0.html

dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).

dict 方法 dict.keys()、dict.items() 和 dict.values() 返回“视图”而不是列表。例如,这不再有效: k = d.keys(); k.sort()。改用 k = sorted(d) (这也适用于 Python 2.5 并且同样有效)。

as I understand it a "view" is an iterator, and an iterator does not have the sort function. Change it to

据我了解,“视图”是一个迭代器,而迭代器没有排序功能。将其更改为

sorted(all_colors)

according to the documentation

根据文档

回答by Klamer Schutte

So the total solution based on Johan's answer is:

因此,基于 Johan 的答案的总解决方案是:

all_colors = sorted(reportlab.lib.colors.getAllNamedColors().items())

回答by Mohammad Heydari

I believe the sort()method doesn't support Python 3.xanymore.

我相信sort()法不支持Python 3.x都有了。

It is necessary to pass the corresponding variable to the sorted(all_colors).

需要将相应的变量传递给sorted(all_colors).