如何使用 python 从逗号分隔一些数字的字符串中提取一些数字?

How to extract some numbers from a character string with comma separating some numbers using python?

假设一个字符串

"1977   1,048.20    1,039.40    894.10  694.70  664.20  1,031.60    928.60  18.80   10:27:05    "

如何提取数字,即

1977    1048.20 1039.40 894.10  694.70  664.20  1031.60 928.60  18.80   10 27 05

如果这个字符串没有逗号分隔,我可以提取数字 数字。但是不知道如何在上述情况下获取它们。

下面是我的代码,用于没有逗号的情况,它不适用于有逗号的情况。

temperaturetime=re.findall(r'\d*\.?\d+',line)

试试下面的代码:

x = "1977   1,048.20    1,039.40    894.10  694.70  664.20  1,031.60    928.60  18.80   10:27:05    "
nums = [float(item) if '.' in item else int(item) for item in x.replace(':', ' ').replace(',', '').split()]
print nums #[1977, 1048.2, 1039.4000000000001, 894.10000000000002, 694.70000000000005, 664.20000000000005, 1031.5999999999999, 928.60000000000002, 18.800000000000001, 10, 27, 5]

如果你想保留逗号,那么 .split() 就可以了。

c = "1977   1,048.20    1,039.40    894.10  694.70  664.20  1,031.60    928.60  18.80   10:27:05    "
print c.split()['1977', '1,048.20', '1,039.40', '894.10', '694.70', '664.20', '1,031.60', '928.60', '18.80', '10:27:05']

如果要删除逗号,

with_comma = c.split()
without_comma = [x.replace(',','') for x in with_comma]
print without_comma
['1977', '1048.20', '1039.40', '894.10', '694.70', '664.20', '1031.60', '928.60', '18.80', '10:27:05']

您输入的最后一个条目似乎格式不同,您必须处理它才能将列表转换为 [float(x) for x in list]