-2

如何将多个变量分配给一个 GUI 输入框?像这样:q1, q2, q3 = input()

这不是代码的样子,但这正是我想要的样子:

 a, b, c = str(input("Type in a command"))

但不是这样:

abc = str(input("Type in a command"))

if abc == str("a"):
    print ("a is right")
else:
    print ("a is wrong")

if abc == str("b"):
    print ("b is right")
else:
    print ("b is wrong")

if abc == str("c"):
    print ("c is right")
else:
    print ("c is wrong")

如果我这样做,我会弄错其中一个,它会告诉我一个是对的,两个是错的。(a错,b对,c错)

4

3 回答 3

3

input只能返回一个字符串,但您可以即时处理它:

a, b, c = input('Type in a command').split()

这可能会导致ValueError输入中“单词”的数量不同于 3,因此您可能需要使用try-except来处理它。

try:
    a, b, c = input('Type in a command').split()
except ValueError:
    print('Invalid input. Please enter a, b and c')
于 2013-01-13T15:00:21.273 回答
1

Input只返回一个字符串。您可以存储输入,然后根据需要对其进行处理。采用多个变量输入的一种简单而安全的方法是:

s = input().split()

在这里,s为您提供空格分隔输入的列表。这可以采用任意数量的选项。

然后,您可以单独处理每个

for i in s :
    if i in ('a','b','c') : 
        print(i, " is right")
    else :
        print(i, " is wrong")
于 2013-01-13T15:01:09.153 回答
0

如果你想使用不同的类型,你可能会使用ast.literal_eval

a,b,c = ast.literal_eval("3,4,5")
a,b,c = ast.literal_eval("3,4.5,'foobar'")

这是有效的,因为ast将字符串评估为包含文字的元组。然后在左侧打开包装。当然,为此,元素必须用逗号分隔。

于 2013-01-13T15:13:45.993 回答