2015-07-11 16 views
1

我想把一個輸入說7 8 9 5 12 17作爲數組ar []中的獨立整數。我試過 a=input() ar.append(a.split(" ")) 但它只是將數字存儲爲字符串。而且我無法找到一種方法來在追加時直接轉換這些整數。請提前幫助感謝。如何在python中進行格式化輸入?

回答

0

要建立一個適當的蟒蛇list對象,你可以做

ar = [int(i) for i in input().split()] 

否則,做這種方式

ar = map(int, input().split()) 

如果需要,還可以去除多餘的空白。不要

ar = map(int, input().strip().split()) 
0

您可以通過列表理解做到這一點。

ar = [int(x) for x in a.strip().split()] 

在這裏,我們首先從strip末的空白和輸入a的開始,然後執行split()。它將以字符串形式返回a中所有數字的列表。然後使用列表理解,我們將所有字符串轉換爲integers

實施例:

對於a' 12 34 45 12 56 '

>>> ar = [int(x) for x in a.strip().split()] 
>>> ar 
[12, 34, 45, 12, 56] 

注:split()操作返回字符串的列表。我們自己將不得不將這些字符串轉換爲整數。

0

內置函數map(function, iterable, ..)可以在這裏用於全部應用int()函數。

ar = map(int, a.split(" "))