所以我有一个列表,playerlocation,我用它作为坐标。坐标是使用input()命令输入的,因此它们显示为字符串而不是整数。我以为这段代码可以解决这个问题,
playerlocation =(input("Player location?"))
playerlocation = list(playerlocation.split(","))
for x in playerlocation:
try:
x = int(x)
coordsareintegers = True
print(playerlocation)
except:
coordsareintegers = False但是print(playerlocation)返回了类似于'1',‘1’的东西,这意味着它们仍然是字符串。
我尝试过在使用坐标的地方使用int()命令,但这真的很繁琐。
发布于 2019-05-28 12:28:25
你可以在你的输入上使用map。类似于:
>>> coords = '1,2'
>>> split = coords.split(',')
>>> split
['1', '2']
>>> ints = map(int, split)
>>> ints
<map object at 0x0000000002476978>
>>> list(ints)
[1, 2]相应地应用于您的代码。
发布于 2019-05-28 12:22:37
除了不断要求用户输入正确的player location format之外,你需要的是一个带有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]https://stackoverflow.com/questions/56334466
复制相似问题