32

首先,我是 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

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

4

3 回答 3

75

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

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

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

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

sorted(all_colors)

根据文档

于 2015-01-20T07:10:01.337 回答
8

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

all_colors = sorted(reportlab.lib.colors.getAllNamedColors().items())
于 2016-10-26T11:28:29.653 回答
3

我相信该sort()方法不再支持Python 3.x。

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

于 2019-10-02T22:17:45.420 回答