我有一个几个整数值的映射,我想迭代它并打印它的值.我试过这个:
n = map(int, input().split())
1 2 3 4 5
for i in n:
print(i)
Run Code Online (Sandbox Code Playgroud)
这给了我一个错误:
ValueError: invalid literal for int() with base 10: ' '
Run Code Online (Sandbox Code Playgroud)
使用上面的相同操作.strip()执行打印整数的工作.
del(n)
n = map(int, input().strip().split())
1 2 3 4 5
for i in n:
print(i)
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
"基数为10的无效文字"是什么意思以及为什么使用.strip()修复错误?另外,地图对象是Python中的单个实体,因为使用时range(map)会给出错误'map'对象不能被解释为整数?
for i in range(n):
print(i)
TypeError: 'map' object cannot be interpreted as an integer
Run Code Online (Sandbox Code Playgroud)
根据我以前的经验,您可能会在打印之前使用地图对象.map返回一个耗材迭代器,因此如果要打印它的值,请确保不要使用它.
例如,
>>> n = map(int, input().strip().split())
1 2 3 4 5
>>> for i in n:
... print(i)
...
1
2
3
4
5
>>> for i in n:
... print(i)
# prints nothing
Run Code Online (Sandbox Code Playgroud)
map 返回一个可以消耗一次而不是两次的生成器.
n = map(int, input().strip().split())
print(*n)
Run Code Online (Sandbox Code Playgroud)
将使用默认分隔符打印它们' '.如果您想根据地图的结果做2件以上的事情,请将其存储在列表中:
n = list( map(int, input().strip().split()) )
Run Code Online (Sandbox Code Playgroud)
所以你不是在生成器上运行 - 列表会保持你的值使用秒/多次.
这个
for i in range(map(int, input().strip().split())):
# do smth
Run Code Online (Sandbox Code Playgroud)
不起作用,因为map <map object at 0x7f9ff77c12b0>不返回所需的整数range.