例如,如果我有一個用戶輸入的被叫num
:如何將用戶輸入存儲到列表中?
num = int(input('Enter numbers'))
我希望能夠將這些號碼存儲到被操縱的列表。 我該如何解決這個問題?謝謝。
例如,如果我有一個用戶輸入的被叫num
:如何將用戶輸入存儲到列表中?
num = int(input('Enter numbers'))
我希望能夠將這些號碼存儲到被操縱的列表。 我該如何解決這個問題?謝謝。
提示「輸入數字」表示用戶將在一行中輸入多個數字,因此拆分該行並將每個數字轉換爲int
。這個列表解析是做到這一點的快捷方法:
numbers = [int(n) for n in input('Enter numbers: ').split()]
以上是Python 3的對於Python 2,使用raw_input()
代替:
numbers = [int(n) for n in raw_input('Enter numbers: ').split()]
在兩種情況下:
>>> numbers = [int(n) for n in raw_input('Enter numbers: ').split()]
Enter numbers: 1 2 3 4 5
>>> numbers
[1, 2, 3, 4, 5]
input_numbers = raw_input("Enter numbers divided by spaces")
input_numbers_list = [int(n) for n in input_numbers.split()]
print input_numbers_list
你可以使用python函數式編程構造函數在一行中做到這一點,稱爲map,
python2
input_list = map(int, raw_input().split())
python3
input_list = map(int, input().split())
輸入:
list_of_inputs = input("Write numbers: ").split()
#.split() will split the inputted numbers and convert it into a list
list_of_inputs= list(map(int , list_of_inputs))
#as the inputted numbers will be saved as a string. This code will convert the string into integers
輸出:
Write numbers: 43 5 78
>>> print (list_of_inputs)
[43, 5, 78]
我是我們ing python 3.6
這會得到一個數字。 – 2015-04-04 04:21:38
定義'L = []'然後'爲我在範圍內(5):L.append(int(input('Enter numbers')))' – 2015-04-04 04:23:51
數字是如何分隔的?像1234或1 2 3 4 – Hackaholic 2015-04-04 04:28:22