“'int' object is not iterable” in while

本秂侑毒 提交于 2021-01-28 20:24:51

问题


def rect_extend(x):
  m, n = 1
  while 1 < x:
    m = m + 1
    n = n + 1
  return m, n

This simple function returns:

'int' object is not iterable

error in iPython. I don't know why it does this, while function doesn't work - condition seems to be true.

(while's condition was simplified on purpose; original code doesn't have it)


回答1:


I think you want

m = 1
n = 1

or

m = n = 1

instead of m, n = 1.

This (sequence unpacking)[http://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences]:

x, y = z

does something different to what you seem to think it does.

It actually means this:

x = z[0]    # The first item in z
y = z[1]    # The second element of z

For instance, you could do this:

x, y, z = (1, 2, 4)

Then:

>>> x
1
>>> y
2
>>> z
4

In your case, you this doesn't work, because 1 is an integer, it doesn't have elements, hence the error.

Useful features of sequence unpacking combined with tuples (and the splat operator - *):

This:

a, b = b, a

swaps the values of a and b.

Unpacking range, useful for constants:

>>> RED, GREEN, BLUE = range(3)
>>> RED
0
>>> GREEN
1
>>> BLUE
2

The splat operator:

>>> first, *middle, last = 1, 2, 3, 4, 5, 6, 7, 8, 9
>>> first
1
>>> middle
[2, 3, 4, 5, 6, 7, 8]
>>> last
9



回答2:


When you do m, n = 1 this is called tuple unpacking, and it works like this:

>>> m, n = ('a','b')
>>> m
'a'
>>> n
'b'

Since 1 is an integer not a tuple, you get this weird error; because Python cannot "step through" (or iterate) an integer to unpack it. That's why the error is 'int' object is not iterable



来源:https://stackoverflow.com/questions/19752637/int-object-is-not-iterable-in-while

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!