【问题标题】:How to set my input to an already existing variable in Python?如何将我的输入设置为 Python 中已经存在的变量?
【发布时间】:2019-10-23 22:58:11
【问题描述】:

我对 python 比较陌生,我不知道该怎么做。我需要从用户那里获取一个数字输入,然后将其转换为一个已经存在的变量。到目前为止,我已经设法接受输入,但我认为我不能将它变成一个变量。我正在尝试将这个输入(数字)添加到字符串的后面(字符串是 pos)

例如,如果我输入数字 1,我将输入 pos1,2 将输入 pos2,依此类推。

if win == 0:
    displayboard()
    newPlot = input("")
    postochange = "pos"+newPlot
    if postochange == "X" or "O":
        print ("Sorry, but that space is taken!")
    else:
        if playerTurn == 1:
            postochange = "X"
        else:
            postochange = "O"

我将尝试进一步简化这一点,我想让用户给我一个数字,我将它添加到文本“pos”中并且对应于我已经的变量em> 有。

【问题讨论】:

  • 您尝试做的事情最好通过列表或字典来完成。查阅在线文档。
  • 您遇到错误了吗?也许您只需要将 newPlot 转换为 str ? posttochange = "pos"+str(newPlot)

标签: python


【解决方案1】:

你能改用值字典吗?例如:

pos_s = {'pos1':None,
         'pos2':None}

pos_s['pos'+str(user_number)] = desired_value

然后要获取变量的值,您可以这样做:

pos_s.get('pos'+str(user_number), None)

【讨论】:

  • 确保 user_numberstring 而不是 int
  • 这行得通,必须更改脚本中的一些其他内容,但它工作正常。感谢您的帮助
【解决方案2】:

只是补充 Mason Caiby 的回答,如果最终用户只能输入有限的值集合,我将使用 set 验证该条目。 然后您可以关联/对应您已经拥有的变量。


# Python program to demonstrate differences 
# between normal and frozen set 

# Same as {"a", "b","c"} 
normal_set = set(["a", "b","c"]) 

# Adding an element to normal set is fine 
normal_set.add("d") 

print("Normal Set") 
print(normal_set) 

# A frozen set 
frozen_set = frozenset(["e", "f", "g"]) 

print("Frozen Set") 
print(frozen_set) 

# Uncommenting below line would cause error as 
# we are trying to add element to a frozen set 
# frozen_set.add("h") 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多