簡體   English   中英

將 Python2 iterkeys() 轉換為 python3

[英]Convert Python2 iterkeys() to python3

我有來自 python2 代碼的這一行:

m = w.iterkeys().next();

當試圖運行它時,我得到:

AttributeError: 'collections.OrderedDict' object has no attribute 'iterkeys'

我發現iterkeys不支持 iterkeys。

如何轉換這一行,以便與 Python3 兼容?

存在用於這種轉換的工具,稱為2to3 ,假設您有code.py文件,其內容如下

import collections
w = collections.OrderedDict(a=1,b=2,c=3)
m = w.iterkeys().next();
print m

然后打開終端並執行2to3 -w code.py ,這確實將code.py更改為

import collections
w = collections.OrderedDict(a=1,b=2,c=3)
m = next(iter(w.keys()));
print(m)

可以與python3一起使用。 原始文件保存為code.py.bak

在 python 3.x 中:

m = w.iterkeys().next()

相當於:

m = list(w.keys())[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM