3 回答

TA貢獻1808條經驗 獲得超4個贊
TypeError: object of type 'enumerate' has no len()
object.__len__(self)
調用以實現內置函數
len()
。應該返回對象的長度,整數 >= 0。
不幸的是,enumerate
返回一個沒有的枚舉對象__len__
:
>>> a = enumerate([1,2,3])
>>> a
<enumerate object at 0x10e496be0>
>>> dir(a)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__',
'__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__']
與list支持的 's不同len():
>>> a = [1,2,3]
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
...
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
...
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
您還可以注意到enumerate 對象也沒有允許您使用like for s__getitem__訪問項目的方法。這就是為什么您在回答中說“它甚至不可下標”。obj[index]list'
我認為我們可以將枚舉對象視為列表。
不,不是。枚舉對象的行為更像一個迭代器,這是 Python 表示可能是無限的“數據流”的方式。您可以通過調用該next()方法來訪問數據,直到引發異常 ( StopIteration)。
重復調用迭代器的__next__()方法(或將其傳遞給內置函數next())會返回流中的連續項。當沒有更多數據可用時,StopIteration會引發異常。
>>> a = enumerate([1,2,3])
>>> next(a)
(0, 1)
>>> next(a)
(1, 2)
>>> next(a)
(2, 3)
>>> next(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
我認為您會認為它們就像list's 一樣,因為您也可以將它們放入像常規一樣的循環結構中list并遍歷每個元素:
>>> a = enumerate([1,2,3])
>>> for i in a:
... print(i)
...
(0, 1)
(1, 2)
(2, 3)
在這種情況下,對于每次迭代,枚舉對象都會提供一個元組,其中包含下一個元素的索引和元素本身。循環的for工作和結束方式與使用enumerate objectnext()的方法時相同。
如enumerate()文檔中所示,list如果您需要類似列表的內容,您可以簡單地將其轉換為 a:
>>> a = list(enumerate([1,2,3]))
>>> a
[(0, 1), (1, 2), (2, 3)]

TA貢獻1943條經驗 獲得超7個贊
enumerate只是為可迭代添加一個計數器,它不是可迭代的。枚舉對象可以轉換為列表,然后可以使用。
至于您的問題,可以使用非枚舉解決方案
def twosum(a, t):
f, l = 0, len(a) - 1
while f <= l:
if a[f] + a[l] == t:
return [a.index(a[f]), a.index(a[l])]
else:
f += 1
l -= 1
twosum([2, 7, 11, 15], 17)
這將返回 [0, 3]。對于枚舉解決方案,
def twosum(a, t):
f, l = 0, len(a)-1
a = list(enumerate(a))
while(f <= l):
if (a[f][1] + a[l][1] == t):
return [a[f][0], a[l][0]]
else:
f += 1
l -= 1
twosum([2, 7, 11, 15], 17)
這也返回 [0, 3]

TA貢獻1816條經驗 獲得超6個贊
這個解決方案奏效了。我必須先將枚舉對象轉換為列表。否則它甚至不能下標。
def twosum(a, t):
a = enumerate(a)
a = sorted(a, key=lambda x:x[1])
f, l = 0, len(a)-1
while(f < l):
if (a[f][1] + a[l][1] == t):
return [a[f][0], a[l][0]]
elif (a[f][1] + a[l][1] < t):
f += 1
else:
l -= 1
添加回答
舉報