Konwertuj wszystkie ciągi znaków na liście do int

W Pythonie chcę przekonwertować wszystkie ciągi znaków z listy na liczby całkowite.

Więc jeśli mam:

results = ['1', '2', '3']

Jak to zrobić:

results = [1, 2, 3]
Author: poke, 2011-09-10

7 answers

Użyj map function (w Pythonie 2.x):

results = map(int, results)

W Pythonie 3, będziesz musiał przekonwertować wynik z map do listy:

results = list(map(int, results))
 1272
Author: cheeken,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-08 15:45:26

Użyj zrozumienie listy :

results = [int(i) for i in results]

Np.

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
 422
Author: Chris Vig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-08 15:47:13

Trochę bardziej rozbudowane niż rozumienie listy, ale równie przydatne:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

Np.

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

Także:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list
 3
Author: 2RMalinowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-14 15:47:47

Oto proste rozwiązanie z wyjaśnieniem twojego zapytania.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Tutaj, append () służy do dodawania elementów (tj. całkowitej wersji string (i) w tym programie) na końcu listy (b).

Notatka: int () jest funkcją, która pomaga przekształcić liczbę całkowitą w postaci ciągu znaków, z powrotem do jej postaci całkowitej.

Konsola wyjściowa:

[1, 2, 3, 4, 5]

Tak więc, możemy przekonwertować pozycje łańcuchowe na liście na liczbę całkowitą tylko wtedy, gdy dany łańcuch jest w całości złożony liczb lub w przeciwnym razie zostanie wygenerowany błąd.

 1
Author: Code Carbonate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-03 09:03:36

Możesz to zrobić po prostu w jednej linii podczas pobierania danych wejściowych.

[int(i) for i in input().split("")]
Podziel się, gdzie chcesz.

Jeśli chcesz przekonwertować listę Nie listę, po prostu umieść nazwę listy w miejscu input().split("").

 0
Author: Achyuta Pataki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-03 14:53:55

Jeśli Twoja lista zawiera czyste ciągi liczb całkowitych, akceptowany awnswer jest właściwą drogą. To rozwiązanie ulegnie awarii, jeśli podasz mu rzeczy, które nie są liczbami całkowitymi.

Więc: jeśli masz dane, które mogą zawierać int, ewentualnie floats lub inne rzeczy, jak również - możesz wykorzystać swoją własną funkcję z errorhandling:

def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)

Wyjście:

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']

Do obsługi iterabli wewnątrz iterabli możesz użyć tego helpera:

from collections.abc import Iterable, Mapping

def convertEr(iterab):
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance(iterab, str):
        return maybeMakeNumber(iterab)

    if isinstance(iterab, Mapping):
        return iterab

    if isinstance(iterab, Iterable):
        return  iterab.__class__(convertEr(p) for p in iterab)


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ("0", "8", {"15", "things"}, "3.141"), "types"]

converted = convertEr(data)
print(converted)

Wyjście:

['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 (0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
 0
Author: Patrick Artner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-18 10:18:17

Chcę również dodać Python / konwertowanie wszystkich łańcuchów w liście na liczby całkowite

Metoda # 1: Metoda Naiwna

# Python3 code to demonstrate 
# converting list of strings to int 
# using naive method 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using naive method to 
# perform conversion 
for i in range(0, len(test_list)): 
    test_list[i] = int(test_list[i]) 
    

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Wyjście:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Metoda # 2: używanie rozumienia listy

# Python3 code to demonstrate 
# converting list of strings to int 
# using list comprehension 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using list comprehension to 
# perform conversion 
test_list = [int(i) for i in test_list] 
    

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Wyjście:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Metoda # 3: Korzystanie z mapy()

# Python3 code to demonstrate 
# converting list of strings to int 
# using map() 

# initializing list 
test_list = ['1', '4', '3', '6', '7'] 

# Printing original list 
print ("Original list is : " + str(test_list)) 

# using map() to 
# perform conversion 
test_list = list(map(int, test_list)) 
    

# Printing modified list 
print ("Modified list is : " + str(test_list)) 

Wyjście:

Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
 0
Author: Mohsin Raza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-28 21:10:22