[英]TypeError: unsupported operand type(s) for +: 'dict_keys' and 'list'
我正在嘗試使用名為 bidi 的 Python 包。 在這個包 (algorithm.py) 的一個模塊中,有一些行給我錯誤,盡管它是包的一部分。
以下是幾行:
_LEAST_GREATER_ODD = lambda x: (x + 1) | 1
_LEAST_GREATER_EVEN = lambda x: (x + 2) & ~1
X2_X5_MAPPINGS = {
'RLE': (_LEAST_GREATER_ODD, 'N'),
'LRE': (_LEAST_GREATER_EVEN, 'N'),
'RLO': (_LEAST_GREATER_ODD, 'R'),
'LRO': (_LEAST_GREATER_EVEN, 'L'),
}
# Added 'B' so X6 won't execute in that case and X8 will run its course
X6_IGNORED = X2_X5_MAPPINGS.keys() + ['BN', 'PDF', 'B']
X9_REMOVED = X2_X5_MAPPINGS.keys() + ['BN', 'PDF']
如果我在 Python 3 中運行代碼,我會收到以下錯誤消息:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
from bidi.algorithm import get_display
File "C:\Python33\lib\site-packages\python_bidi-0.3.4-py3.3.egg\bidi\algorithm.py", line 41, in <module>
X6_IGNORED = X2_X5_MAPPINGS.keys() + ['BN', 'PDF', 'B']
TypeError: unsupported operand type(s) for +: 'dict_keys' and 'list'
盡管這是比迪套餐的一部分,但為什么會出現此錯誤? 和我的 Python 版本有關系嗎? 我很感激這方面的任何幫助。
在 Python 3.x 中, dict.keys
返回一個字典視圖:
>>> a = {1:1, 2:2}
>>> a.keys()
dict_keys([1, 2])
>>> type(a.keys())
<class 'dict_keys'>
>>>
您可以通過將這些視圖放在list
來獲得您想要的內容:
X6_IGNORED = list(X2_X5_MAPPINGS.keys()) + ['BN', 'PDF', 'B']
X9_REMOVED = list(X2_X5_MAPPINGS.keys()) + ['BN', 'PDF']
實際上,您甚至不再需要.keys
,因為迭代字典會產生它的鍵:
X6_IGNORED = list(X2_X5_MAPPINGS) + ['BN', 'PDF', 'B']
X9_REMOVED = list(X2_X5_MAPPINGS) + ['BN', 'PDF']
是的,這與您的 Python 版本有關。 在 Python 2.x 中, dict.keys
返回字典鍵的列表。 在 Python 3.x 中,它提供了鍵的視圖對象。
您可以對結果調用list()
以使其成為列表,或者只是在整個字典上調用list()
作為快捷方式。
在 Python 3.x 中, dict.keys
不返回列表,而是返回view
對象dict_keys
。
要實現您想要的,您需要將其轉換為列表:
X6_IGNORED = list(X2_X5_MAPPINGS.keys()) + ['BN', 'PDF', 'B']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.