2012-04-27 21 views
12

Jak przekonwertować spację całkowitą z oddzielnymi liczbami całkowitymi na listę liczb całkowitych?Konwertowanie listy ciągów na listę liczb całkowitych

Przykład Wejście:

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

Przykład konwersji:

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

Możliwy duplikat [Konwersja wszystkie sznurki w liście do int] (http://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) –

Odpowiedz

31

map() jest twoim przyjacielem, to stosuje się funkcję podaną jako pierwszy argument do wszystkich pozycji na liście.

map(int, yourlist) 

ponieważ odwzorowuje każdy iterable, można nawet zrobić:

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

który (w python3.x) zwraca obiekt mapy, które mogą być zamienione na liście. Zakładam, że jesteś na python3, ponieważ użyłeś input, a nie raw_input.

+1

+ 1 ale czy miałeś na myśli 'map (int, yourlist)'? –

+0

oczywiście, już edytowane. – ch3ka

+0

masz na myśli 'map (int, input(). Split())', czy też py3k automatycznie konwertuje dane rozdzielone spacjami na listę? – quodlibetor

1

Można spróbować:

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

To nie działa. 'int' nie jest metodą na łańcuchach. –

+0

Przepraszam, że to zredagowałem ... Tak naprawdę to miałem na myśli :) – Silviu

+0

To nie jest źle, ale generalnie nie użyłbym ponownie tego "x". –

14

Jednym ze sposobów jest użycie wyrażeń listowych:

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

+1, '[int (x) dla x na wejściu(). Split()]' w celu dostosowania specyfikacji OP. – georg

-2

prostu ciekawy temat sposobu Got '1', '2', '3', ' 4 'zamiast 1, 2, 3, 4. W każdym razie.

>>> 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'] 

porządku, jakiś kod

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

to działa:

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

Twój wtrącenie jest zepsute. –

1

Say jest listą ciągów nazwie list_of_strings i wyjście jest lista liczb nazwanych list_of_int. map funkcja jest wbudowaną funkcją python, która może być użyta do tej operacji.

'''Python 2.7''' 
list_of_strings = ['11','12','13'] 
list_of_int = map(int,list_of_strings) 
print list_of_int 
Powiązane problemy