由于这里不重要的原因,我有一个excel表格,其中我的数字有小数点的逗号以及数千个分隔符。区分逗号应该是小数还是千位分隔符的唯一方法是逗号后面的位数:
decimal = 7,29
thousands = 23,767,209
我的方法,适用于我的情况,是将数字读入字符串并执行以下代码:
strings = ["0", "87,390,112", "78", "9,27", "1"]
strings_new = []
for i in strings:
if len(i) >= 3:
# check if third last char is a comma --> decimal
if i[-3] == ',':
i = i[:-3] + '.' + i[-3 + 1:]
if len(i) >= 4:
# check if fourth last char is a comma --> all commas are thousands
if i[-4] == ',':
i = i.replace(",", "")
strings_new.append(i)
strings_new = [float(i) for i in strings_new]
输出看起来很好:
strings_new = [0.0, 87390112.0, 78.0, 9.27, 1.0]
是否有任何特殊情况,我没有想到这个代码?是否有更有效的方法来解决这个问题?
两种情况:
100,1
。使用i.rfind(',')
获取逗号位置,而不是使用-3
对其进行硬编码。10,000,24
。它将通过第二个if子句(10,000.24
)。总是在没有if子句的情况下运行i.replace(",", "")
应该没问题。