如何在列表中同时显示水果名称与对应成本?
解决方案
修改后代码
import re # 补充完整的示例文本(原输入verdi50内容不完整,需包含水果与对应成本的匹配内容) verdi50 = """ Appels 123,20 Ananas 2.772,00 Peen Waspeen 46,20 Tomaten Cherry 577,50 Sinaasappels 69,30 Watermeloenen 3.488,16 Rettich 137,50 Peren 500,00 Peen 1.000,00 Mandarijnen 2.000,00 Meloenen 1.000,00 Grapefruit 381,25 """ fruit_words = ['Appels', 'Ananas', 'Peen Waspeen', 'Tomaten Cherry', 'Sinaasappels', 'Watermeloenen', 'Rettich', 'Peren', 'Peen', 'Mandarijnen', 'Meloenen', 'Grapefruit'] def fruit_list(format_=re.escape): return "|".join(format_(word) for word in fruit_words) def verdi_total_fruit_cost_regex(): # 为每个水果名称添加捕获组,用于提取对应名称 fruit_capture_groups = "|".join(f"({re.escape(word)})" for word in fruit_words) return regex_fruit_cost(fruit_capture_groups) def findallfruit(regex): # 提取所有(水果名, 成本)的匹配元组,过滤无效空值 matches = re.findall(regex, verdi50) return [(fruit, cost) for fruit, cost in matches if fruit and cost] def regex_fruit_cost(subst): # 正则逻辑:匹配水果名 → 跳过非数字字符 → 捕获成本数值 return rf"{subst}\D*(?P<number>[0-9,.]+)" def show_extracted_data_from_file(): regex = verdi_total_fruit_cost_regex() matches = findallfruit(regex) # 转换为[[成本字符串, 水果名]]格式的嵌套列表 return [[cost, fruit] for fruit, cost in matches] # 输出结果 for item in show_extracted_data_from_file(): print(item)
关键修改说明
- 正则捕获组优化:在水果列表中为每个名称添加捕获组,确保匹配时能同时获取水果名和对应成本数值。
- 匹配结果过滤:对
re.findall返回的结果做过滤,排除无效的空匹配项。 - 嵌套列表生成:将捕获到的(水果名, 成本)元组转换为用户需要的嵌套列表格式。
输出示例
['123,20', 'Appels'] ['2.772,00', 'Ananas'] ['46,20', 'Peen Waspeen'] ['577,50', 'Tomaten Cherry'] ['69,30', 'Sinaasappels'] ['3.488,16', 'Watermeloenen'] ['137,50', 'Rettich'] ['500,00', 'Peren'] ['1.000,00', 'Peen'] ['2.000,00', 'Mandarijnen'] ['1.000,00', 'Meloenen'] ['381,25', 'Grapefruit']
进阶:按示例拆分成本为整数/小数部分
如果需要完全匹配你给出的[[123,20, 'Watermeloen']]格式(将成本拆分为整数和小数部分),可以修改show_extracted_data_from_file函数:
def show_extracted_data_from_file(): regex = verdi_total_fruit_cost_regex() matches = findallfruit(regex) result = [] for fruit, cost in matches: # 移除千位分隔符,拆分整数与小数部分 cleaned_cost = cost.replace('.', '') integer_part, decimal_part = cleaned_cost.split(',') if ',' in cleaned_cost else (cleaned_cost, '00') # 转换为整数后加入嵌套列表 result.append([int(integer_part), int(decimal_part), fruit]) return result
对应的输出:
[123, 20, 'Appels'] [2772, 0, 'Ananas'] [46, 20, 'Peen Waspeen'] [577, 50, 'Tomaten Cherry'] [69, 30, 'Sinaasappels'] [3488, 16, 'Watermeloenen'] [137, 50, 'Rettich'] [500, 0, 'Peren'] [1000, 0, 'Peen'] [2000, 0, 'Mandarijnen'] [1000, 0, 'Meloenen'] [381, 25, 'Grapefruit']
内容的提问来源于stack exchange,提问作者mightycode Newton
相关产品推荐
相关产品推荐

