Python嵌套列表过滤时如何对指定索引元素做减法计算并替换
问题根因
- 已编写的减法逻辑没有实际生效:计算完成后未将结果做格式转换、未替换原条目的对应位置值,直接把原始子列表追加进了
results,导致输出始终是原始价格字符串。 - 用
set生成的国家列表不保证顺序,会让预先定义的minimal_values、maximal_values和对应国家匹配错位,影响阈值判断的准确性。
修正思路
- 替换原有的国家列表生成逻辑,按
my_list里国家首次出现的顺序提取唯一值,保证和阈值列表的定义顺序完全对应 - 对符合阈值条件的条目,执行指定减法后将浮点结果格式化为逗号分隔的两位小数字符串,匹配原有数据格式
- 构造新的条目,保留原条目的国家、品类、最后一列阈值值,把计算好的新价格放到第三个位置,再加入结果列表
可直接运行的修正代码
my_value = 500 minimal_values = ['0,32', '0,35', '0,45'] maximal_values = ['0,78', '0,85', '0,72'] my_list = [ ['Morocco', 'Meat', '190,00', '0,15'], ['Morocco', 'Meat', '189,90', '0,32'], ['Morocco', 'Meat', '189,38', '0,44'], ['Morocco', 'Meat', '188,94', '0,60'], ['Morocco', 'Meat', '188,49', '0,78'], ['Morocco', 'Meat', '187,99', '0,101'], ['Spain', 'Meat', '190,76', '0,10'], ['Spain', 'Meat', '190,16', '0,20'], ['Spain', 'Meat', '189,56', '0,35'], ['Spain', 'Meat', '189,01', '0,40'], ['Spain', 'Meat', '188,13', '0,75'], ['Spain', 'Meat', '187,95', '0,85'], ['Italy', 'Meat', '190,20', '0,11'], ['Italy', 'Meat', '190,10', '0,31'], ['Italy', 'Meat', '189,32', '0,45'], ['Italy', 'Meat', '188,61', '0,67'], ['Italy', 'Meat', '188,01', '0,72'], ['Italy', 'Meat', '187,36', '0,80'] ] # 转换阈值为浮点数 minimal_values = [float(i.replace(',', '.')) for i in minimal_values] maximal_values = [float(i.replace(',', '.')) for i in maximal_values] # 按首次出现顺序提取唯一国家,和阈值顺序一一对应 countries = [] for item in my_list: if item[0] not in countries: countries.append(item[0]) results = [] for item in my_list: country_idx = countries.index(item[0]) threshold_value = float(item[-1].replace(',', '.')) # 判断条目是否在对应国家的阈值范围内 if minimal_values[country_idx] <= threshold_value <= maximal_values[country_idx]: original_price = float(item[-2].replace(',', '.')) calc_result = my_value - original_price # 格式化为两位小数,替换小数点为逗号,匹配原数据格式 formatted_price = f"{calc_result:.2f}".replace('.', ',') # 构造新条目,替换第三个位置的价格值 new_entry = [item[0], item[1], formatted_price, item[-1]] results.append(new_entry) # 输出结果验证 for row in results: print(row)
代码运行后输出
完全匹配预期格式:
['Morocco', 'Meat', '310,10', '0,32'] ['Morocco', 'Meat', '310,62', '0,44'] ['Morocco', 'Meat', '311,06', '0,60'] ['Morocco', 'Meat', '311,51', '0,78'] ['Spain', 'Meat', '310,44', '0,35'] ['Spain', 'Meat', '310,99', '0,40'] ['Spain', 'Meat', '311,87', '0,75'] ['Spain', 'Meat', '312,05', '0,85'] ['Italy', 'Meat', '310,68', '0,45'] ['Italy', 'Meat', '311,39', '0,67'] ['Italy', 'Meat', '311,99', '0,72']
内容的提问来源于stack exchange,提问作者TangerCity
相关产品推荐
相关产品推荐

