如何从用户输入一个整数元组?

14

目前我正在做这个

print 'Enter source'
source = tuple(sys.stdin.readline())

print 'Enter target'
target = tuple(sys.stdin.readline())

但在这种情况下,源和目标将成为带有 \n 结尾的字符串元组。


(n, m) = tuple(map(int, input().split(" "))) (n,m)= tuple(map(int,input()。split(“”))) - quintin
4个回答

16
tuple(int(x.strip()) for x in raw_input().split(','))

现在用户应该如何输入?我尝试了4,0...但它不起作用。 - Bruce
我得到了以下输出结果 - 输入源 0,4 输入目标 3,2 ('0', '4') ('3', '2') - Bruce
啊,我稍微修改了我的答案。请将你的内容与我写的进行比较。 - Ignacio Vazquez-Abrams
4
sys.stdin.readline()可以在Python2和Python3中使用,其优点在于跨版本兼容。在Python3中,raw_input已被重命名为input - John La Rooy

7
原来,int函数可以很好地去除空格,所以没有必要使用strip函数。
tuple(map(int,raw_input().split(',')))

例如:

>>> tuple(map(int,"3,4".split(',')))
(3, 4)
>>> tuple(map(int," 1 , 2 ".split(',')))
(1, 2)

1

如果您仍希望用户被提示两次等等。

print 'Enter source'
source = sys.stdin.readline().strip()  #strip removes the \n

print 'Enter target'
target = sys.stdin.readline().strip()

myTuple = tuple([int(source), int(target)])

这可能不太符合Python的风格,但更具有教学意义...


源和目标都是元组。我们可以在元组上使用int()函数。 - Bruce
抱歉,所需的输出不清楚。无论如何,string.strip()和int()应该能帮助你获得你需要的内容,可以是两个包含单个整数的元组,或者一个包含源值和目标值的元组。 - mjv

0
t= tuple([eval(x) for x in input("enter the values: ").split(',')])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接