Reputation: 17
I'm new to Python, sorry for the level of this question.
This is my output (prices from a website). I'm wondering how to convert them into a list of int
s
for price_list_items in price_list:
for values in price_list_items:
x= values.rstrip(' zł')
print(x)
479 000
355 000
269 000
499 000
289 000
The desired result will like this [479 000,355 000,... ]. Also, I want to be able to perform basic with the values. I found this thread How to convert a for loop output into a list (python), but it didn't help me.
Upvotes: 0
Views: 5826
Reputation: 4606
lista = []
for price_list_items in price_list:
for values in price_list_items:
x= values.rstrip(' zł')
lsita.append(x)
lista = ['479 000', '350 000']
for idx, item in enumerate(lista):
item = item.split()
item = ''.join(item)
lista[idx] = int(item)
print(lista)
~/python/stack$ python3.7 sum.py [479000, 350000]
Change your last line to append
to lista
instead of print
. Now we have lista = ['479 000', ...]
but we want int
s to perform operations on.
So we can then enumerate
our list
, from there we can split()
and join()
to get to here lista = ['479000', ...]
then we can just use int(item)
and put them back into lista
as int
s
For fun we could do some map
and just go from:
lista = ['479 000', '350 000']
lista = list(map(lambda x: int(''.join((x.split()))), lista))
Upvotes: 1
Reputation: 8010
It looks like your string is meant to be a series of 6-digit numbers but both the individual number-parts, for lack of a better term, are split by spaces and the numbers themselves are split by newlines. The solution, therefore, is to remove the space in between number-parts, converting the result to an integer, like this:
int(part.replace(' ', '')) # Finds all instances of space and replaces them with nothing
Putting this in a list-comprehension, we have:
numbers = [int(l.replace(' ', '')) for l in str]
UPDATE
Since you've posted your code, I can give you a better answer.
[ int(v.rstrip(' zł').replace(' ', '')) for price_list_items in price_list for v in price_list_items ]
Upvotes: 0