I have a list with numeric strings, like so:
numbers = ["1", "5", "10", "8"];
I would like to convert every list element to integer, so it would look like this:
numbers = [1, 5, 10, 8];
I could do it using a loop, like so:
new_numbers = ; for n in numbers: new_numbers.append(int(n)); numbers = new_numbers;
Does it have to be so ugly? I"m sure there is a more pythonic way to do this in a one line of code. Please help me out.
This is what list comprehensions are for:
numbers = [ int(x) for x in numbers ]
In Python 2.x another approach is to use
numbers = map(int, numbers)
Note: in Python 3.x
map returns a map object which you can convert to a list if you want:
numbers = list(map(int, numbers))
In the last decade, we have seen the impact of exponential advances in technology on the way we work, shop, communicate, and think. At the heart of this change is our ability to collect and gain insig...
In Learn Python 3 the Hard Way PDF, you'll learn Python by working through 52 brilliantly crafted exercises. Read them. Enter your code exactly. (No copying and pasting!) Correct your mistakes. ...
We live in an age of so-called Big Data. We hear terms like data scientist, and there is much talk about analytics and the mining of large amounts of corporate data for tidbits of business value. Ther...
Why this Book? Hadoop has been the base for most of the emerging technologies in today’s big data world. It changed the face of distributed processing by using commodity hardware for large data set...