How do I convert all strings in a list to integers?
['1', '2', '3'] ⟶ [1, 2, 3]
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)
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]
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
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]
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]
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
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
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.
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("").
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]
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.
Related
This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 8 months ago.
The community is reviewing whether to reopen this question as of 11 days ago.
I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,
myList.append(munfunc())
How should I convert the returned result to a string in order to join it with the list?
Do I need to do the following for every integer value:
myList.append(str(myfunc()))
Is there a more Pythonic way to solve casting problems?
Calling str(...) is the Pythonic way to convert something to a string.
You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:
print(','.join(str(x) for x in list_of_ints))
There's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like
', '.join(map(str, myList))
The map function in python can be used. It takes two arguments. The first argument is the function which has to be used for each element of the list. The second argument is the iterable.
a = [1, 2, 3]
map(str, a)
['1', '2', '3']
After converting the list into a string you can use the simple join function to combine the list into a single string
a = map(str, a)
''.join(a)
'123'
There are three ways of doing this.
let say you have a list of integers
my_list = [100,200,300]
"-".join(str(n) for n in my_list)
"-".join([str(n) for n in my_list])
"-".join(map(str, my_list))
However as stated in the example of timeit on python website at https://docs.python.org/2/library/timeit.html using a map is faster. So I would recommend you using "-".join(map(str, my_list))
a=[1,2,3]
b=[str(x) for x in a]
print b
above method is the easiest and most general way to convert list into string. another short method is-
a=[1,2,3]
b=map(str,a)
print b
Your problem is rather clear. Perhaps you're looking for extend, to add all elements of another list to an existing list:
>>> x = [1,2]
>>> x.extend([3,4,5])
>>> x
[1, 2, 3, 4, 5]
If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.
>>> x = ['1', '2']
>>> x.extend([str(i) for i in range(3, 6)])
>>> x
['1', '2', '3', '4', '5']
All of this is considered pythonic (ok, a generator expression is even more pythonic but let's stay simple and on topic)
For example:
lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]
lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']
As to me, I want to add a str before each str list:
# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']
Or single list:
lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
Maybe you do not need numbers as strings, just do:
functaulu = [munfunc(arg) for arg in range(loppu)]
Later if you need it as string you can do it with string or with format string:
print "Vastaus5 = %s" % functaulu[5]
How come no-one seems to like repr?
python 3.7.2:
>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>>
Take care though, it's an explicit representation. An example shows:
#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>>
more info at pydocs-repr
I have an imported data file.
It is a list made up of 51 lists.
Each of the nested lists has 5 elements.
I want to change 1 (The second element so location 1) of the 5 elements from string to integers.
This is what I have:
for i in range(len(statesData)):
statesData[i] = statesData[i].strip()
statesData[i] = statesData[i].split(',')
for d in statesData[i]:
d[1] = int(d[1])
d[2] = float(d[2])
Now I don't want element 1 (0) to be included since it is the heading of each category.
I want to start with 2 (1). I was thinking a range function somewhere like:
statesData[i][1:]
But that doesn't seem to work. Any advice? I should be able to do this without too much trouble. Or having to create a function.
In your second loop, you are looping over each element of the nested lists, i.e. when you're doing d[1] you are indexing the string of said element. Try this instead
for i in range(len(statesData)):
print(statesData[i])
statesData[i] = statesData[i].strip()
statesData[i] = statesData[i].split(',')
statesData[i][1] = int(statesData[i][1])
statesData[i][2] = float(statesData[i][2])
If you have a list of lists only containing integers similar to this
t = [['0', '1', '2', '3', '4'], ['0', '5', '6', '7', '8']]
you can change the type of all elements except the first for each list with a list comprehension like this:
mod_t = [[l[0]] + [int(e) for e in l[1:]] for l in t]
# [['0', 1, 2, 3, 4], ['0', 5, 6, 7, 8]]
Explanations:
You walk through all list elements of t with for l in t
For each of those lists, you'll generate a new list with the original first element l[0] and integer converted elements for all subsequent items [int(e) for e in l[1:]]
First point, semantically, your list should be a list of tuples, not a list of lists (if position is significant then it's a tuple - a list is supposed to be an homogeneous collection).
Also, changing the list in place is mostly a useless complication, specially for such a small dataset. The simplest solution is to build a new list from the existing one, ie:
def parse_row(row):
return (row[0], int(row[1]), float(row[2])) + row[3:]
def parse_data(data):
return [parse_row(row) for row in data]
if __name__ == "__main__":
state_data = [
("foo", "1", "1.5", "a", "b"),
("bar", "2", "2.5", "c", "d"),
("baaz", "3", "3.5", "e", "f"),
("quux", "4", "4.5", "g", "h"),
]
print(parse_data(state_data))
wrt/ your issue:
for d in statesData[i]:
d[1] = int(d[1])
d[2] = float(d[2])
here, statesData[i] is your current sublist, so the iteration variable d is successively rebound to each of your sublist's elements.
You could go with the following which is pretty concise:
for i, sd in enumerate(statesData):
sd = sd.strip().split(',')
if i: # omit first (index 0) from further processing
sd[1:3] = int(sd[1]), float(sd[2])
statesData[i] = sd
For this problem I am dealing with a big list,that it was imported from a CSV file, but let's say
I have a list like this:
[['name','score1','score2''score3''score4']
['Mike','5','1','6','2']
['Mike','1','1','1','1']
['Mike','3','0','3','0']
['jose','0','1','2','3']
['jose','2','3','4','5']
['lisa','4','4','4','4']]
and I want to have another list with this form(the sum of all score for each student):
[['Mike','9','2','10','3']
['jose','2','4','6','8']
['lisa','4','4','4','4']]
any ideas how this can be done?
I've been trying many ways, and I could not make it.
I was stuck when there where more than 2 same names, my solution only kept the last 2 lines to add.
I am new in python and programming in general.
If you are just learning Python I always recommend try to implement things without relying on external libraries. A good starting step is to start by trying to break the problem up into smaller components:
Remove the first entry (the column titles) from the input list. You don't need it for your result.
For each remaining entry:
Convert every entry except the first to an integer (so you can add them).
Determine if you have already encountered an entry with the same name (first column value). If not: add the entry to the output list. Otherwise: merge the entry with the one already in the output list (by adding values in the columns).
One possible implementation follows (untested):
input_list = [['name','score1','score2''score3''score4'],
['Mike','5','1','6','2'],
['Mike','1','1','1','1'],
['Mike','3','0','3','0'],
['jose','0','1','2','3'],
['jose','2','3','4','5'],
['lisa','4','4','4','4']]
print input_list
# Remove the first element
input_list = input_list[1:]
# Initialize an empty output list
output_list = []
# Iterate through each entry in the input
for val in input_list:
# Determine if key is already in output list
for ent in output_list:
if ent[0] == val[0]:
# The value is already in the output list (so merge them)
for i in range(1, len(ent)):
# We convert to int and back to str
# This could be done elsewhere (or not at all...)
ent[i] = str(int(ent[i]) + int(val[i]))
break
else:
# The value wasn't in the output list (so add it)
# This is a useful feature of the for loop, the following
# is only executed if the break command wasn't reached above
output_list.append(val)
#print input_list
print output_list
The above is not as efficient as using a dictionary or importing a library that can perform the same operation in a couple of lines, however it demonstrates a few features of the language. Be careful when working with lists though, the above modifies the input list (try un-commenting the print statement for the input list at the end).
Let us say you have
In [45]: temp
Out[45]:
[['Mike', '5', '1', '6', '2'],
['Mike', '1', '1', '1', '1'],
['Mike', '3', '0', '3', '0'],
['jose', '0', '1', '2', '3'],
['jose', '2', '3', '4', '5'],
['lisa', '4', '4', '4', '4']]
Then, you can use Pandas ...
import pandas as pd
temp = pd.DataFrame(temp)
def test(m):
try: return int(m)
except: return m
temp = temp.applymap(test)
print temp.groupby(0).agg(sum)
If you are importing it from a cvs file, you can directly read the file using pd.read_csv
You could use better solution as suggested but if you'd like to implement yourself and learn, you can follow and I will explain in comments:
# utilities for iteration. groupby makes groups from a collection
from itertools import groupby
# implementation of common, simple operations such as
# multiplication, getting an item from a list
from operator import itemgetter
def my_sum(groups):
return [
ls[0] if i == 0 else str(sum(map(int, ls))) # keep first one since it's name, sum otherwise
for i, ls in enumerate(zip(*groups)) # transpose elements and give number to each
]
# list comprehension to make a list from another list
# group lists according to first element and apply our function on grouped elements
# groupby reveals group key and elements but key isn't needed so it's set to underscore
result = [my_sum(g) for _, g in groupby(ls, key=itemgetter(0))]
To understand this code, you need to know about list comprehension, * operator, (int, enumerate, map, str, zip) built-ins and some handy modules, itertools and operator.
You edited to add header which will break our code so we need to remove it such that we need to pass ls[1:] to groupby instead of ls. Hope it helps.
As a beginner I would consider turning your data into a simpler structure like a dictionary, so that you are just summing a list of list. Assuming you get rid of the header row then you can turn this into a dictionary:
>>> data_dict = {}
>>> for row in data:
... data_dict.setdefault(row[0], []).append([int(i) for i in row[1:]])
>>> data_dict
{'Mike': [[5, 1, 6, 2], [1, 1, 1, 1], [3, 0, 3, 0]],
'jose': [[0, 1, 2, 3], [2, 3, 4, 5]],
'lisa': [[4, 4, 4, 4]]}
Now it should be relatively easy to loop over the dict and sum up the lists (you may want to look a sum and zip as a way to do that.
This is well suited for collections.Counter
from collections import Counter, defaultdict
csvdata = [['name','score1','score2','score3','score4'],
['Mike','5','1','6','2'],
['Mike','1','1','1','1'],
['Mike','3','0','3','0'],
['jose','0','1','2','3'],
['jose','2','3','4','5'],
['lisa','4','4','4','4']]
student_scores = defaultdict(Counter)
score_titles = csvdata[0][1:]
for row in csvdata[1:]:
student = row[0]
scores = dict(zip(score_titles, map(int, row[1:])))
student_scores[student] += Counter(scores)
print(student_scores["Mike"])
# >>> Counter({'score3':10, 'score1':9, 'score4':3, 'score2':2})
collections.defaultdict
I am new to Python. I need to know how to convert a list of integers to a list of strings. So,
>>>list=[1,2,3,4]
I want to convert that list to this:
>>>print (list)
['1','2','3','4']
Also, can I add a list of strings to make it look something like this?
1234
You can use List Comprehension:
>>> my_list = [1, 2, 3, 4]
>>> [str(v) for v in my_list]
['1', '2', '3', '4']
or map():
>>> str_list = map(str, my_list)
>>> str_list
['1', '2', '3', '4']
In Python 3, you would need to use - list(map(str, my_list))
For 2nd part, you can use join():
>>> ''.join(str_list)
'1234'
And please don't name your list list. It shadows the built-in list.
>>>l=[1,2,3,4]
I've modified your example to not use the name list -- it shadows the actual builtin list, which will cause mysterious failures.
Here's how you make it into a list of strings:
l = [str(n) for n in l]
And here's how you make them all abut one another:
all_together = ''.join(l)
Using print:
>>> mylist = [1,2,3,4]
>>> print ('{}'*len(mylist)).format(*mylist)
1234
l = map(str,l)
will work, but may not make sense if you don't know what map is
l = [str(x) for x in l]
May make more sense at this time.
''.join(["1","2","3"]) == "123"
This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 8 months ago.
The community reviewed whether to reopen this question 16 days ago and left it closed:
Original close reason(s) were not resolved
I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,
myList.append(munfunc())
How should I convert the returned result to a string in order to join it with the list?
Do I need to do the following for every integer value:
myList.append(str(myfunc()))
Is there a more Pythonic way to solve casting problems?
Calling str(...) is the Pythonic way to convert something to a string.
You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:
print(','.join(str(x) for x in list_of_ints))
There's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like
', '.join(map(str, myList))
The map function in python can be used. It takes two arguments. The first argument is the function which has to be used for each element of the list. The second argument is the iterable.
a = [1, 2, 3]
map(str, a)
['1', '2', '3']
After converting the list into a string you can use the simple join function to combine the list into a single string
a = map(str, a)
''.join(a)
'123'
There are three ways of doing this.
let say you have a list of integers
my_list = [100,200,300]
"-".join(str(n) for n in my_list)
"-".join([str(n) for n in my_list])
"-".join(map(str, my_list))
However as stated in the example of timeit on python website at https://docs.python.org/2/library/timeit.html using a map is faster. So I would recommend you using "-".join(map(str, my_list))
a=[1,2,3]
b=[str(x) for x in a]
print b
above method is the easiest and most general way to convert list into string. another short method is-
a=[1,2,3]
b=map(str,a)
print b
Your problem is rather clear. Perhaps you're looking for extend, to add all elements of another list to an existing list:
>>> x = [1,2]
>>> x.extend([3,4,5])
>>> x
[1, 2, 3, 4, 5]
If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.
>>> x = ['1', '2']
>>> x.extend([str(i) for i in range(3, 6)])
>>> x
['1', '2', '3', '4', '5']
All of this is considered pythonic (ok, a generator expression is even more pythonic but let's stay simple and on topic)
For example:
lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]
lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']
As to me, I want to add a str before each str list:
# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']
Or single list:
lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
Maybe you do not need numbers as strings, just do:
functaulu = [munfunc(arg) for arg in range(loppu)]
Later if you need it as string you can do it with string or with format string:
print "Vastaus5 = %s" % functaulu[5]
How come no-one seems to like repr?
python 3.7.2:
>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>>
Take care though, it's an explicit representation. An example shows:
#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>>
more info at pydocs-repr