Python 这些行应将列表中的所有对象更改为整数,但它们';你仍然以字符串的形式出现
所以我有一个列表,playerlocation,我用它作为坐标。坐标是通过input()命令输入的,因此它们显示为字符串而不是整数。我以为这段代码可以解决这个问题Python 这些行应将列表中的所有对象更改为整数,但它们';你仍然以字符串的形式出现,python,python-3.x,Python,Python 3.x,所以我有一个列表,playerlocation,我用它作为坐标。坐标是通过input()命令输入的,因此它们显示为字符串而不是整数。我以为这段代码可以解决这个问题 playerlocation=(输入(“玩家位置?”) playerlocation=list(playerlocation.split(“,”)) 对于playerlocation中的x: 尝试: x=int(x) coordsareintegers=真 打印(播放位置) 除: coordsareintegers=错误 但是pri
playerlocation=(输入(“玩家位置?”)
playerlocation=list(playerlocation.split(“,”))
对于playerlocation中的x:
尝试:
x=int(x)
coordsareintegers=真
打印(播放位置)
除:
coordsareintegers=错误
但是print(playerlocation)
返回类似于['1','1',这意味着它们仍然是字符串
我曾尝试在使用坐标的任何位置使用
int()
命令,但这确实很乏味。您需要的是使用try进行while循环,只是不断要求用户输入正确的播放器位置格式,如果条目是逗号分隔的有效整数,它将退出循环并打印播放器位置:
while True:
try:
x, y = input("Player location: ").split(',')
player_location = [int(x), int(y)]
print('player location:', player_location)
break
except:
print('error: you should enter an integers x,y for player location, try again!\n')
示例输出:
Player location: blah..blah
error: you should enter an integers x,y for player location, try again!
Player location: 3,4
player location: [3, 4]
您可以在输入中使用map
。比如:
>>> coords = '1,2'
>>> split = coords.split(',')
>>> split
['1', '2']
>>> ints = map(int, split)
>>> ints
<map object at 0x0000000002476978>
>>> list(ints)
[1, 2]
协调='1,2'
>>>split=coords.split(',')
>>>分裂
['1', '2']
>>>ints=映射(int,拆分)
>>>ints
>>>列表(ints)
[1, 2]
相应地应用于您的代码。
int(input())
?我应该包括playerlocation=(input(“Player location?”))上面的两行playerlocation=list(playerlocation.split(“,”))项被输入为x,y坐标,然后字符串被拆分