Python3如何从字符串中提取各类十进制数并转换为float类型
Python3 混合字符串数字提取及统计实现方案
实现逻辑
使用正则匹配定位字符串中所有符合要求的十进制数,过滤掉$符号后转换为float类型即可,无需额外处理前导零,Python的float转换会自动保留对应数值。
修改后完整代码
import re def mode(x): if len(x) == 0: return 0 else: theDictionary = {} for number in x: count = theDictionary.get(number, None) if count == None: theDictionary[number] = 1 else: theDictionary[number] = count + 1 theMaximum = max(theDictionary.values()) for key in theDictionary: if theDictionary[key] == theMaximum: print("Mode: ", key) return key def median(x): if len(x) == 0: return 0 else: x.sort() midpoint = len(x) // 2 print("Median: ", end=" ") if len(x) % 2 == 1: print(x[midpoint]) med = x[midpoint] else: print((x[midpoint] + x[midpoint - 1]) / 2) med = (x[midpoint] + x[midpoint - 1]) / 2 return med def mean(x): if len(x) == 0: return 0 else: theSum = 0.0 for number in x: theSum += number average = theSum / len(x) print("Mean: ", average) return average def main(): print ("Enter a list of numbers or enter to quit: ") numbers = input() if numbers == "": return 0 else: # 核心修改:正则提取所有符合要求的数字 pattern = r'\$?\d+\.?\d*' matches = re.findall(pattern, numbers) lyst = [float(match.lstrip('$')) for match in matches] print("List: ", lyst) mode(lyst) median(lyst) mean(lyst) main() if __name__ == "__main__": main()
适配验证
输入样例字符串 5, 7 83 100, $5.07, and 7.834 时,提取得到的数字列表为 [5.0, 7.0, 83.0, 100.0, 5.07, 7.834],完全覆盖需求场景:
- 支持整数、小数提取
- 支持带$前缀的金额提取
- 自动忽略字符串中的标点、普通文本内容
- 带前导零的数值转换后精度保留正常
内容的提问来源于stack exchange,提问作者David G
相关产品推荐
相关产品推荐

