Ando
Ando

Reputation: 85

How to make every object in a list a float

I'm using Python 2. When I try to multiply objects in a list it just repeats the same thing twice even though i have tried to use this to resolve the issue:

map(float, prices)

The code i'm using is:

import urllib
from bs4 import BeautifulSoup

prices = []
htmlfile = urllib.urlopen("http://www.fifacoin.com/default/quick/listwithcategoryid?        category_id=6").read()
soup = BeautifulSoup(htmlfile)
for item in soup.find_all('tr', {'data-price': True}):
    prices.append(item['data-price'])

map(float, prices)
print prices[1] * 2

This code just outputs the value of prices 2. I'm new to Python so it's probably something obvious

Upvotes: 1

Views: 87

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 113955

You could try a list comprehension:

answer = [float(i) for i in prices]

Output:

In [253]: prices
Out[253]: ['5', '1', '3', '8']

In [254]: [float(i) for i in prices]
Out[254]: [5.0, 1.0, 3.0, 8.0]

In [255]: prices
Out[255]: ['5', '1', '3', '8']

Note that the original list remains unchanged

Upvotes: 2

tckmn
tckmn

Reputation: 59283

map does not change the original list; it simply returns a new list. Try:

prices = map(float, prices)

Upvotes: 5

Related Questions