2012-04-27 188 views
12

如何將空格分隔的整數輸入轉換爲整數列表?將字符串列表轉換爲整數列表

例輸入:

list1 = list(input("Enter the unfriendly numbers: ")) 

轉換例:

['1', '2', '3', '4', '5'] to [1, 2, 3, 4, 5] 
+0

[轉換所有字符串在列表中INT]可能的複製(http://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – 2016-04-15 07:13:20

回答

31

map()是你的朋友,它適用給出第一個參數列表中的所有項目的功能。

map(int, yourlist) 

因爲它映射每個迭代,你甚至可以這樣做:

map(int, input("Enter the unfriendly numbers: ")) 

這(在python3.x)返回一個地圖對象,它可以被轉換成一個列表。 我假設你使用python3,因爲你使用了input而不是raw_input

+1

+ 1但你的意思是'map(int,yourlist)'?當然, – 2012-04-27 13:48:21

+0

已經編輯過了。 – ch3ka 2012-04-27 13:48:36

+0

你是指'map(int,input().split())',還是py3k自動將空格分隔的輸入轉換成列表? – quodlibetor 2012-04-27 14:23:00

1

你可以試試:

x = [int(n) for n in x] 
+2

這不起作用。 'int'不是字符串的一種方法。 – 2012-04-27 13:49:06

+0

對不起,我編輯了它......這實際上是我的意思:) – Silviu 2012-04-27 13:51:52

+0

這沒有錯,但我通常不會重複使用'x'。 – 2012-04-27 13:53:54

14

的方法之一是使用列表理解:

intlist = [int(x) for x in stringlist] 
+0

+1,'[int(x)for input()。split()]'符合OP的規格。 – georg 2012-04-27 14:34:23

-2

只是好奇你得到的方式 '1', '2', '3',' 4'而不是1,2,3,4。

>>> list1 = list(input("Enter the unfriendly numbers: ")) 
Enter the unfriendly numbers: 1, 2, 3, 4 
>>> list1 = list(input("Enter the unfriendly numbers: ")) 
Enter the unfriendly numbers: [1, 2, 3, 4] 
>>> list1 
[1, 2, 3, 4] 
>>> list1 = list(input("Enter the unfriendly numbers: ")) 
Enter the unfriendly numbers: '1234' 
>>> list1 = list(input("Enter the unfriendly numbers: ")) 
Enter the unfriendly numbers: '1', '2', '3', '4' 
>>> list1 
['1', '2', '3', '4'] 

好了,一些代碼

>>> list1 = input("Enter the unfriendly numbers: ") 
Enter the unfriendly numbers: map(int, ['1', '2', '3', '4']) 
>>> list1 
[1, 2, 3, 4] 
3

這個工程:

nums = [int(x) for x in intstringlist] 
0
l=['1','2','3','4','5'] 

for i in range(0,len(l)): 
    l[i]=int(l[i]) 
+0

您的縮進被打破。 – 2012-07-24 06:45:15

1

說,有一個名爲爲List_Of_Strings和輸出是一個名爲的整數列表字符串列表list_of_intmap函數是一個可用於此操作的內置python函數。

'''Python 2.7''' 
list_of_strings = ['11','12','13'] 
list_of_int = map(int,list_of_strings) 
print list_of_int 
相關問題