>>> [int(x) for x in raw_input().split()]
1 2 3 5 100
[1, 2, 3, 5, 100]
^{pr2}$
創建一個按空格分隔的新列表,然后[int(x) for x in raw_input().split()]
將此新列表中的每個字符串轉換為整數。在list()
是一個函數,它從諸如>>> list({1, 2, 3}) # constructs list from a set {1, 2, 3}
[1, 2, 3]
>>> list('123') # constructs list from a string
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3] # constructs list from a tuple
所以>>> list('1 2 3 5 100')
['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']
list函數還可以遍歷字符串,并將每個字符追加到新列表中。但是,您需要用空格分隔,因此list函數不合適。在
input接受字符串并將其轉換為對象'1 2 3 5 100'
不是有效的python對象,它是由空格分隔的5個數字。
考慮一下打字,把這個弄清楚>>> 1 2 3 5 100
SyntaxError: invalid syntax
變成一個Python殼。這只是無效的語法。所以input也會引起這個錯誤。在
重要的是:
input不是一個安全的函數,因此即使您的字符串是{},您也不應該使用input,因為有害的python代碼可以通過input執行。
如果出現這種情況,請使用ast.literal_eval:>>> import ast
>>> ast.literal_eval('[1,2,3,5,100]')
[1, 2, 3, 5, 100]
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态