“只能迭代". Python错误 [英] "Can only iterable" Python error
问题描述
你好,我的程序员们.
我是一个相当新的程序员,现在我面临着巨大的困境.我收到错误消息:
can only assign an iterable
首先我不知道那是什么意思.
第二,我将我的代码留给您的专业人员进行批判:
def num_top(int_lis):
duplic_int_lis = int_lis
int_firs= duplic_int_lis [0]
int_lis[:] = duplic_int_lis [int_firs]
基本上,我试图在列表中找到[0]
元素,然后使用该int作为索引位置来找到该索引位置处的整数.
int_lis[:] = duplic_int_lis [int_firs]
意味着将duplic_int_lis [int_firs]
的所有项分配给int_lis
,因此希望您在RHS上传递可迭代/迭代器.>
但是在您的情况下,您将其传递为不可迭代的,这是不正确的:
>>> lis = range(10)
>>> lis[:] = range(5)
>>> lis #all items of `lis` replaced with range(5)
[0, 1, 2, 3, 4]
>>> lis[:] = 5 #Non-iterable will raise an error.
Traceback (most recent call last):
File "<ipython-input-77-0704f8a4410d>", line 1, in <module>
lis[:] = 5
TypeError: can only assign an iterable
>>> lis[:] = 'foobar' #works for any iterable/iterator
>>> lis
['f', 'o', 'o', 'b', 'a', 'r']
由于您不能迭代整数,因此会出现错误.
>>> for x in 1: pass
Traceback (most recent call last):
File "<ipython-input-84-416802313c58>", line 1, in <module>
for x in 1:pass
TypeError: 'int' object is not iterable
Hello my fellow programmers.
I am a fairly new programmer, and now I am facing a great predicament. I am getting the error:
can only assign an iterable
Firstly I don't know what that means.
Secondly I will leave my code for you professionals to critique it:
def num_top(int_lis):
duplic_int_lis = int_lis
int_firs= duplic_int_lis [0]
int_lis[:] = duplic_int_lis [int_firs]
Basically I am trying to find the [0]
element in the list and then using that int as an index position to find the integer at that index position.
int_lis[:] = duplic_int_lis [int_firs]
means assign all the items of duplic_int_lis [int_firs]
to int_lis
, so it expects you to pass an iterable/iterator on the RHS.
But in your case you're passing it an non-iterable, which is incorrect:
>>> lis = range(10)
>>> lis[:] = range(5)
>>> lis #all items of `lis` replaced with range(5)
[0, 1, 2, 3, 4]
>>> lis[:] = 5 #Non-iterable will raise an error.
Traceback (most recent call last):
File "<ipython-input-77-0704f8a4410d>", line 1, in <module>
lis[:] = 5
TypeError: can only assign an iterable
>>> lis[:] = 'foobar' #works for any iterable/iterator
>>> lis
['f', 'o', 'o', 'b', 'a', 'r']
As you cannot iterate over an integer, hence the error.
>>> for x in 1: pass
Traceback (most recent call last):
File "<ipython-input-84-416802313c58>", line 1, in <module>
for x in 1:pass
TypeError: 'int' object is not iterable
这篇关于“只能迭代". Python错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!