Python中的for循环如何遍历unsubscriptable对象? [重复]

时间:2022-07-24 19:27:50

This question already has an answer here:

这个问题在这里已有答案:

How can the for loop in Python iterate through objects that I cannot address using the [n] notation?

Python中的for循环如何迭代使用[n]表示法无法解决的对象?

Consider this:

考虑一下:

myCollection # Some objects with elements (not a simple list)
for elem in myCollection:
    print elem.Title
myCollection[0]

The code above would in my case succeed in the for loop and will print the title string of all the elements, while the call to myCollection[0] would fail with the following exception:

在我的情况下,上面的代码将在for循环中成功并将打印所有元素的标题字符串,而对myCollection [0]的调用将失败,并出现以下异常:

TypeError: 'myCollection' object is unsubscriptable

How does the for statement iterate through the objects?

for语句如何遍历对象?

Is there another way to access the first element of the collection when the subscript notation fails?

当下标符号失败时,是否有另一种方法来访问集合的第一个元素?

Background

This comes up in IronPython scripting in the Spotfire application which is why I cannot give a MWE.

这出现在Spotfire应用程序中的IronPython脚本中,这就是我无法提供MWE的原因。

Here is a dir(myCollection):

这是一个目录(myCollection):

['Equals', 'GetHashCode', 'GetType', 'Item', 'MemberwiseClone', 'Overloads',   'ReferenceEquals', 'ToString', '__call__', '__class__', '__cmp__', '__delattr__', '__delete__', '__doc__', '__get__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__']

to illustrate the methods defined on this object. It does not have a next or next method and for loops still work here.

说明在此对象上定义的方法。它没有下一个或下一个方法,并且循环仍然在这里工作。

1 个解决方案

#1


0  

The forloop works by calling the private__next__() method, which returns a value.

forloop通过调用private__next __()方法来工作,该方法返回一个值。

#1


0  

The forloop works by calling the private__next__() method, which returns a value.

forloop通过调用private__next __()方法来工作,该方法返回一个值。