ChatGPT解决这个技术问题 Extra ChatGPT

Convert all strings in a list to int

How do I convert all strings in a list to integers?

['1', '2', '3']  ⟶  [1, 2, 3]

M
Mateen Ulhaq

Given:

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

In Python 2, use map to obtain a list of integers:

map(int, xs)

In Python 3, apply list after map to obtain a list of integers:

list(map(int, xs))

I want to point out that pylint discourages the use of map, so prepare to use list comprehensions anyway if you ever use that standard. :)
The inverse is ( to convert a list of int to list of string ) : map( str, results)
You can simplify this answer: just always use list(map(int, results)), it works for any Python version.
I just want to add for the map function its type is an iterable so technically if you were to iterate through it you wouldn't need to convert it into a list.
geting error in python3: ValueError: invalid literal for int() with base 10: '['
M
Mateen Ulhaq

Use a list comprehension on the list xs:

[int(x) for x in xs]

e.g.

>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]

List comprehension is great too. To the OP - see here for to see a nice contrast of map and list comprehension: stackoverflow.com/questions/1247486/…
E
Eric Aya

You can easily convert string list items into int items using loop shorthand in python

Say you have a string result = ['1','2','3']

Just do,

result = [int(item) for item in result]
print(result)

It'll give you output like

[1,2,3]

The same solution has already been posted above.
P
Patrick Artner

If your list contains pure integer strings, the accepted answer is the way to go. It will crash if you give it things that are not integers.

So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with 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)

Output:

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

To also handle iterables inside iterables you can use this helper:

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)

Output:

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

S
Shubhank Gupta

There are several methods to convert string numbers in a list to integers.

In Python 2.x you can use the map function:

>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]

Here, It returns the list of elements after applying the function.

In Python 3.x you can use the same map

>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]

Unlike python 2.x, Here map function will return map object i.e. iterator which will yield the result(values) one by one that's the reason further we need to add a function named as list which will be applied to all the iterable items.

Refer to the image below for the return value of the map function and it's type in the case of python 3.x

https://i.stack.imgur.com/YRQck.png

The third method which is common for both python 2.x and python 3.x i.e List Comprehensions

>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

C
Community

A little bit more expanded than list comprehension but likewise useful:

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)

e.g.

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

Also:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

C
Code Carbonate

Here is a simple solution with explanation for your query.

 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)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.


B
Boruto Uzumaki

You can do it simply in one line when taking input.

[int(i) for i in input().split("")]

Split it where you want.

If you want to convert a list not list simply put your list name in the place of input().split("").


M
Mohsin Raza

I also want to add Python | Converting all strings in list to integers

Method #1 : Naive Method

# 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)) 

Output:

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

Method #2 : Using list comprehension

# 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)) 

Output:

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

Method #3 : Using map()

# 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)) 

Output:

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

You should consider adding performance metrics to the approaches you show. For example, which is faster: list comp or map? i.e. map
W
Wojciech Moszczyński

The answers below, even the most popular ones, do not work for all situations. I have such a solution for super resistant thrust str. I had such a thing:

AA = ['0', '0.5', '0.5', '0.1', '0.1', '0.1', '0.1']

AA = pd.DataFrame(AA, dtype=np.float64)
AA = AA.values.flatten()
AA = list(AA.flatten())
AA

[0.0, 0.5, 0.5, 0.1, 0.1, 0.1, 0.1]

You can laugh, but it works.