我有以下列表。
导入日期时间
my_list = [
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0),'0,012'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0),'0,153'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,114'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,109'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,252'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,012'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,113'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,116'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,250'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,266']]
通过以下代码,我获得了每个国家的最高价值。然而,这是正确的。我还想将该国家添加到max_price_per_list
max_prices_by_country = {}
for item in my_list:
price = max_prices_by_country.setdefault(item[0], 0)
max_prices_by_country[item[0]] = max(price, float(item[-1].replace(',', '.')))
country = item[0]
max_price_per_list = [[country] + [str(price).replace('.', ',') for price in max_prices_by_country.values()]]
print(max_price_per_list)
这是我当前的输出:
[['Spain', '0,252', '0,266']]
这是我的首选输出:
[[Morocco, '0,252'],
['Spain', '0,266']]
也许你可以这样做
import datetime
my_list = [
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0),'0,012'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0),'0,153'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,114'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,109'],
['Morocco', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,252'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,012'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,113'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,116'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,250'],
['Spain', 'Fish', datetime.datetime(2020, 11, 17, 0, 0), '0,266']]
max_prices_by_country = {}
for item in my_list:
country = item[0]
# if country is not in dict add it with a value, 0
if country not in max_prices_by_country:
max_prices_by_country[country] = 0
# get the max value of existing and incoming value (which is item[0])
max_prices_by_country[country] = max(max_prices_by_country[country], float(item[-1].replace(',', '.')))
# convert the dict to a list of array.
max_price_per_list = [[k, str(max_prices_by_country[k]).replace('.', ',')] for k in max_prices_by_country]
print(max_price_per_list)
对于程序的最后一部分,您似乎正在尝试将dictionary扁平化为列表。
你可以做一些不会像这样长的命令:
max_price_per_list = list(max_prices_by_country.items())