我想从标准输入读取五个数字输入如下:
3,4,5,1,8
分成变量a,b,c,d和e.
我怎么在python中这样做?
我试过这个:
import string
a=input()
b=a.split(', ')
两个整数,但它不起作用.我明白了:
Traceback (most recent call last):
  File "C:\Users\Desktop\comb.py", line 3, in <module>
    b=a.split(', ')
AttributeError: 'tuple' object has no attribute 'split'
这该怎么做?并假设我没有固定但可变数n个整数.然后?
its*_*dok 15
用raw_input()而不是input().
# Python 2.5.4
>>> a = raw_input()
3, 4, 5
>>> a
'3, 4, 5'
>>> b = a.split(', ')
>>> b
['3', '4', '5']
>>> [s.strip() for s in raw_input().split(",")] # one liner
3, 4, 5
['3', '4', '5']
误导性的名称input功能并没有达到你所期望的那样.它实际上将stdin的输入计算为python代码.
在你的情况下,事实证明你所拥有的是一个数字元组a,所有解析并准备工作,但通常你并不真的想要使用这种奇怪的副作用.其他输入可能导致任何数量的事情发生.
顺便说一句,在Python 3中,他们修复了这个问题,现在该input功能可以满足你的期望.
还有两件事:
import string简单的字符串操作.开箱:
>>> l = (1,2,3,4,5)
>>> a,b,c,d,e = l
>>> e
5
| 归档时间: | 
 | 
| 查看次数: | 28638 次 | 
| 最近记录: |