Not sure my title is clear enough. I have the following list :
[u'394', u'132.2k', u'6.8k', u'1', u'100', u'457', u'3.5k', u'3.5k', u'184', u'507', u'57']
I want to loop over this list, delete all the K, and when deleting them multiply the element by 1000. So I guess I need to convert each string as an interger before multiplying it.
I tried various recipe but I'm kind of lost. Here is what I've done until now :
for item in stringlist:
if 'k' in item:
finallist.append(item)
however this doesn't work at all because it return me a list of k
without any numbers. I also tried to use replace
but couldn't make it work.
I know that's is really easy to convert strings into integers but that's not my main issue here...
Try this:
start_list = [u'394', u'132.2k', u'6.8k', u'1', u'100', u'457', u'3.5k', u'3.5k', u'184', u'507', u'57']
end_list = [int(1000*float(x.replace('k', ''))) if 'k' in x else int(x) for x in start_list]
print(end_list)
prints:
[394, 132200, 6800, 1, 100, 457, 3500, 3500, 184, 507, 57]
EDIT: we can make this a little more robust, in case of empty elements, as so (spaced out for legibility):
start_list = [u'394', u'132.2k', u'6.8k', u'1', u'100', u'457', u'3.5k', u'3.5k', u'184', u'507', u'57', u'.', u'1.2']
end_list = [int(1000*float(x.replace('k', ''))) if 'k' in x
else int(float('0' + x + '0')) if '.' in x
else int(x)
for x in start_list]
print(end_list)
by adding a '0'
to either side of any element with a .
(but no k
) in it, we capture the empty case of u'.'
. Note that this will round decimal values, with the output as follows:
[394, 132200, 6800, 1, 100, 457, 3500, 3500, 184, 507, 57, 0, 1]
You could use a regular expression to determine whether you have a regular number, or a "k" number (both "3k" and "3.0k" will yield 3000).
Update: as a bonus, this one also deals with "M" for Mega and "G" for Giga :-)
import re
ds = [u'394', u'132.2k', u'6.8k', u'7k', u'9.7G', u'18.1M']
factors = {'k': 1e3, 'M': 1e6, 'G': 1e9}
def f(s):
mo = re.match(r'(\d+(?:\.\d+)?)([kMG])?', s)
return int(float(mo.group(1)) * factors.get(mo.group(2), 1))
print([f(d) for d in ds])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.