dict_items对象没有“sort”属性

2024-06-09 09:44:34 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我对Python还不熟悉。我正在使用PTVShttp://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


Tags: httpsgithubmastercomitemsallsortblob
3条回答

只是一个理论:你用的是Python3!

来自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).

据我所知,“视图”是一个迭代器,迭代器没有排序函数。把它改成

sorted(all_colors)

根据文件

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

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

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

必须将相应的变量传递给sorted(all_colors)

相关问题 更多 >