可以使用字典:
d = {'': 1, 'm': 1e6, 'b': 1e9, 't': 1e12}
a = [float(number) * d[unit[:1]]
for s in a
for number, _, unit in [s.partition(' ')]]
或者用科学记数法替换那些 illions:
a = [float(s.replace(' million', 'e6')
.replace(' billion', 'e9')
.replace(' trillion', 'e12'))
for s in a]
用您的列表乘以 1000 对结果进行基准测试:
Round 1 Round 2 Round 3
3640 us 3618 us 3555 us original
2747 us 2738 us 2706 us Kelly1
2258 us 2272 us 2214 us Kelly2
3759 us 3841 us 3802 us dim_an
3495 us 3542 us 3562 us motyzk
基准代码(Try it online!):
from timeit import timeit
def baseline(a):
pass
def original(a):
for i in range(len(a)):
num_phrase=''
if ' ' in a[i]:
num_phrase=a[i].split(" ")[1]
if num_phrase=="million":
a[i]=float(a[i].split(" ")[0])*1000000
elif num_phrase=="billion":
a[i]=float(a[i].split(" ")[0])*1000000000
elif num_phrase=="trillion":
a[i]=float(a[i].split(" ")[0])*1000000000000
else:
a[i]=float(a[i].split(" ")[0])
return a
def Kelly1(a):
d = {'': 1, 'm': 1e6, 'b': 1e9, 't': 1e12}
return [float(number) * d[unit[:1]]
for s in a
for number, _, unit in [s.partition(' ')]]
def Kelly2(a):
return [float(s.replace(' million', 'e6')
.replace(' billion', 'e9')
.replace(' trillion', 'e12'))
for s in a]
def dim_an(a):
multipliers = {
"million": 10 ** 6,
"billion": 10 ** 9,
"trillion": 10 ** 12,
}
for i in range(len(a)):
words = a[i].split()
if len(words) == 0 or len(words) > 2:
raise ValueError("Bad string: " + e)
result = float(words[0])
if len(words) == 2:
result *= multipliers[words[1]]
a[i] = result
return a
def motyzk(a):
str_to_num = {
"": 1,
"million": 1000000,
"billion": 1000000000,
"trillion": 1000000000000,
}
for i in range(len(a)):
num_phrase=''
if ' ' in a[i]:
num_phrase=a[i].split(" ")[1]
a[i]=float(a[i].split(" ")[0])*str_to_num[num_phrase]
return a
# config
funcs = original, Kelly1, Kelly2, dim_an, motyzk, baseline
a = ["10", "1000" , "1.684 million", "356852", "2.5 billion", "3 trillion"] * 1000
number = 100
# correctness
expect = original(a.copy())
for func in funcs:
result = func(a.copy())
print(result == expect, func.__name__)
# speed
tss = [[] for _ in funcs]
for _ in range(3):
print('Round 1 Round 2 Round 3')
for func, ts in zip(funcs, tss):
t = timeit(lambda: func(a.copy()), number=number) / number
ts.append(t)
print(*('%4d us ' % (t * 1e6) for t in ts), func.__name__)
print()