Convert All Strings in a List to Int

Convert all strings in a list to int

Given:

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

Use map then list to obtain a list of integers:

list(map(int, xs))

In Python 2, list was unnecessary since map returned a list:

map(int, xs)

How to convert all strings in the list to int

Just as you tried, you can do it recursively:

def recursive_sum(lst):
if not lst:
return 0
else:
return int(lst[0]) + recursive_sum(lst[1:])

print(recursive_sum([1, 2, 3]))
# 6

If you want to input the numbers, just do:

print(recursive_sum(input().split()))

converting list of integers ,numerical strings into a integer list

Here's how to do it below I explain with code comments.

def solve(lst):
# Dictionary of words to numbers
NUMBERS_DIC = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90}

# list to be returned
retLst = []
for num in lst:
# if num is an int
if type(num)==int: # type() tells you the type of the variable
retLst.append(num)
# if num is a string that is numeric
elif num.isnumeric():
retLst.append(int(num)) # Turn to int
# if num is a string word such as forty-seven"
else:
# turns "forty-seven" -> ["forty","seven"]
word_values_lst = num.split("-")
val = 0
for word in word_values_lst:
val+=NUMBERS_DIC[word] # Get value from NUMBERS_DIC
retLst.append(val)



# Sort lst
retLst.sort()


return list(set(retLst)) # removes duplicates


lst = [1, 3, '4', '1', 'three', 'eleven', 'forty-seven', '3']
retLst = solve(lst)

print(retLst)


Convert string list of lists to integer in python

This should help you:

lst = [['1 2 3'], ['4 5 6'],['7 8 9']]
lst = [elem.split(' ') for lstt in lst for elem in lstt]
lst = [[int(num) for num in lstt[:]] for lstt in lst]

Output:

>>> lst
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In Python, how do I convert all of the items in a list to floats?

[float(i) for i in lst]

to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.

Converting list items from string to int(Python)

You should do this:

for i in range(len(Student_Grades)):
Student_Grades[i] = int(Student_Grades[i])

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

int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:

>>> int("1") + 1
2

If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 3:

T2 = [list(map(int, x)) for x in T1]

In Python 2:

T2 = [map(int, x) for x in T1]


Related Topics



Leave a reply



Submit