我有一个巨大的txt文件,具有以下值(前5个):
$42,198.98
$1,305.04
$1,821.91
$105,747.79
$100,931.55
如何将此字符串列表转换为数字列表(意味着删除“ $”和“,”)?
infile = open('sample.txt', 'r')
list_2016 = [line.rstrip() for line in infile]
infile.close()
list_2016 = [i[1:] for i in list_2016] # dropping $
list_2016 = [list_2016.replace(',', '') for i in list_2016] # dropping ','
list_2016 = [float(x) for x in list_2016]
答案 0 :(得分:4)
不是最优雅的,但是:
s = "$42,198.98 $1,305.04 $1,821.91 $105,747.79 $100,931.55"
f = [float(x) for x in s.replace("$",'').replace(',','').split()]
print(f) # [42198.98, 1305.04, 1821.91, 105747.79, 100931.55]
想法:
.split()
方法,默认情况下,该方法会在空白处进行分割