如何在python中使数字可迭代?



如何在python中迭代整数集合或者如何在python中将数字集合变成列表?

当我试图迭代整数时,我得到了错误。

TypeError: 'int' object is not iterable

输入n = 7849 9594 9699

n = input()
n1, n2, n3 = list(map(int, n.split(' ')))
for i in n1:
print(i)

回溯(最近一次调用):

File "E:/Python code/wipro - 2.py",第5行,

for I in n1:

TypeError: 'int' object is not iterable

我的问题是如何使n1可迭代或者如何将n1 n2 n3转换成列表?

我希望
n1 = 7849 (as list)
n2 = 9594 (as list)
n3 = 9699 (as list)

这样我就可以在n1 n2 n3上执行列表函数

提前感谢!

如果您需要一个列表,则不需要在拆分后使用三个对象。

使用这个命令在分割输入后得到一个列表:

n = input()
n1 = list(map(int, n.split(' ')))
for i in n1:
print(i)

听起来混乱是"作为一个列表"的想法。我猜你想要的是

n1 = ['7', '8', '4', '9']
n2 = ['9', '5', '9', '4']
n3 = ['9', '6', '9', '9']

所以你可以直接用

n1, n2, n3 = list(map(list, n.split(' ')))

之类的。这里有优化的空间,但是在不知道你的用例的情况下,很难说什么是完美的。

最新更新