【发布时间】:2021-01-05 07:33:56
【问题描述】:
我有以下 3 个列表:
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,70'],
['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,55']]
如果index [-1] 介于minimal_values 中的值和maximal_values 中的值之间,我正在尝试过滤my_list。这些值是按国家/地区划分的最小值和最大值。我也在列表中做减法。所以对于摩洛哥,我只想要index[-1] 介于0,32 和0,78 等之间的行。问题是在0,78 之后值下降到0,70,这意味着该行也满足if 语句。
注意:my_list-1中的值是先升后降的。我只想要升序部分的行,而不是降序部分的行。我不确定如何解决这个问题。
这是我的代码:
price = 500
# Convert values to float.
minimal_values = [float(i.replace(',', '.')) for i in minimal_values]
maximal_values = [float(i.replace(',', '.')) for i in maximal_values]
# Collect all unique countries in a list.
countries = list(set(country[0] for country in my_list))
results = []
for l in my_list:
i = countries.index(l[0])
if minimal_values[i] <= float(l[-1].replace(',', '.')) <= maximal_values[i]:
new_index_2 = price - float(l[-2].replace(',', '.'))
l[-2] = new_index_2
results.append(l)
print(results)
这是我当前的输出:
[['Morocco', 'Meat', '189.90', '0,32'],
['Morocco', 'Meat', 310.62, '0,44'],
['Morocco', 'Meat', 311.06, '0,60'],
['Morocco', 'Meat', 311.51, '0,78'],
['Morocco', 'Meat', 312.01, '0,70'],
['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'],
['Italy', 'Meat', 312.64, '0,55']]
这是我想要的输出:
[['Morocco', 'Meat', '189.90', '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']]
*****熊猫相关的回答也欢迎。
【问题讨论】:
-
这似乎是一个安静有趣的案例。我很想知道如何解决这个问题。
-
是的,我也是。虽然我猜是安静的复杂。
-
你有没有考虑过使用 pandas 来完成这个任务(可能还有更多类似这样的任务......)对于这类任务,内置了更直观和直接的操作......
-
我不确定如何专门为此使用 padnas。
-
添加到您接受涉及熊猫的解决方案的问题。
标签: python pandas list if-statement floating-point