3 回答

TA貢獻1871條經驗 獲得超8個贊
中的input函數python將整行作為str.
因此,如果您輸入一個以空格分隔的整數列表,該input函數會將整行作為字符串返回。
>>> a = input()
1 2 3 4 5
>>> type(a)
<class 'str'>
>>> a
'1 2 3 4 5'
如果要將其保存為整數列表,則必須遵循以下過程。
>>> a = input()
1 2 3 4 5
>>> a
'1 2 3 4 5'
現在,我們需要將字符串中的數字分開,即拆分字符串。
>>> a = a.strip().split() # .strip() will simply get rid of trailing whitespaces
>>> a
['1', '2', '3', '4', '5']
我們現在有了 a listof strings,我們必須將它轉換為 a listof ints。我們必須調用int()的每個元素,list最好的方法是使用map函數。
>>> a = map(int, a)
>>> a
<map object at 0x0081B510>
>>> a = list(a) # map() returns a map object which is a generator, it has to be converted to a list
>>> a
[1, 2, 3, 4, 5]
我們終于有list一個ints
整個過程主要在一行python代碼中完成:
>>> a = list(map(int, input().strip().split()))
1 2 3 4 5 6
>>> a
[1, 2, 3, 4, 5, 6]

TA貢獻1828條經驗 獲得超4個贊
從用戶那里獲取帶有空格的輸入:
strength = list(map(int, input().strip().split()))
對它們進行排序:
strength.sort()
并打?。?/p>
print(strength)

TA貢獻1803條經驗 獲得超6個贊
首先,my_list = [20 10 50 400 100 500]它既不是列表,也不是表示列表的正確方式。您使用 代表一個列表my_list = [20, 10 ,50, 400, 100, 500]。
我會假設my_list是一個字符串。因此,您將字符串拆分為列表,將列表轉換為整數,然后對其進行排序,如下所示
my_list = "20 10 50 400 100 500"
li = [int(item) for item in my_list.split(' ')]
print(sorted(li))
#[10, 20, 50, 100, 400, 500]
為了使您的原始代碼工作,我們會做
strength = input()
strength_li = [int(item) for item in strength.split(' ')]
print(sorted(strength_li))
輸出看起來像。
10 20 40 30 60
#[10, 20, 30, 40, 60]
添加回答
舉報