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

时间:2010-02-10 01:57:53

标签: python

目前我正在这样做

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

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

但是源和目标在这种情况下成为字符串元组,最后是

4 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:6)

事实证明int在删除空格方面做得非常好,因此无需使用strip

tuple(map(int,raw_input().split(',')))

例如:

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

答案 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)])

这可能不那么pythonic,但更多教诲......

答案 3 :(得分:0)

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