Und*_*ryx 50 python list raw-input
我尝试使用raw_input()
获取数字列表,但是使用代码
numbers = raw_input()
print len(numbers)
Run Code Online (Sandbox Code Playgroud)
输入[1,2,3]
给出了结果7
,所以我猜它将输入解释为是一个字符串.有没有直接的方法来制作清单?也许我可以re.findall
用来提取整数,但如果可能的话,我宁愿使用更多的Pythonic解决方案.
gre*_*tec 79
在Python 3.x中,使用它.
a = [int(x) for x in input().split()]
Run Code Online (Sandbox Code Playgroud)
>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 56
解析由空格分隔的数字列表要容易得多,而不是尝试解析Python语法:
Python 3:
s = input()
numbers = list(map(int, s.split()))
Run Code Online (Sandbox Code Playgroud)
Python 2:
s = raw_input()
numbers = map(int, s.split())
Run Code Online (Sandbox Code Playgroud)
eval(a_string)
将字符串计算为Python代码.显然这不是特别安全.通过使用模块中的literal_eval
函数,您可以获得更安全(更受限制)的评估ast
.
raw_input()
在Python 2.x中称为它,因为它是原始的,而不是"解释"的输入.input()
解释输入,即相当于eval(raw_input())
.
在Python 3.x中,input()
做什么raw_input()
用来做什么,如果这就是你想要的(即你必须手动评估的内容eval(input())
).
您可以使用 .split()
numbers = raw_input().split(",")
print len(numbers)
Run Code Online (Sandbox Code Playgroud)
这仍然会给你字符串,但它将是一个字符串列表.
如果需要将它们映射到类型,请使用list comprehension:
numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)
Run Code Online (Sandbox Code Playgroud)
如果你希望能够在进入任何 Python类型,并自动映射和你信任你的用户的隐式,那么你可以使用eval
另一种方法是使用 for 循环。假设您希望用户在名为“memo”的列表中输入 10 个数字
memo=[]
for i in range (10):
x=int(input("enter no. \n"))
memo.insert(i,x)
i+=1
print(memo)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
414635 次 |
最近记录: |