如何从python列表组件生成dict

2024-10-01 02:18:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份日期清单:

dates = ['2018-11-13 ', '2018-11-14 ']

我有一份不同城市的天气数据清单:

weather_data = [('Carbondale', 1875.341, '2018-11-13 '), ('Carbondale', 1286.16, '2018-11-14 '), ('Davenport', 708.5, '2018-11-13 '), ('Davenport', 506.1, '2018-11-14 ')]

i[1]在天气数据中是基于每天的气候信息的气候得分。为了这个例子,我缩短了上面的列表。你知道吗

我的目标是找到每天气候得分最低的城市。我想一个好办法是把它们放进字典里。你知道吗

我想要的一个例子是。。。你知道吗

conditions_dict = {'2018-11-13': ('Carbondale',1875.341), ('Davenport', 708.5)}

我的最终结果是。。。你知道吗

The best weather on 2018-11-13 is in Davenport with a value of 708.5

基本上,如果我有一个以日期为键,以(城市,值)为值的dict,那么我就可以很容易地按城市找到每天的最低值。你知道吗

然而,我不知道怎样把我的字典做成这样。我真正纠结的部分是如何在一天内将日期与不同城市的多个读数相匹配。你知道吗

使用字典是一个很好的方法吗?你知道吗


Tags: 数据信息目标列表data字典dict例子
2条回答

如果您的目标是找到每个日期的最低分数和城市,那么您实际上不需要一个包含所有城市和每个日期分数的中间dict,因为您可以简单地遍历weather_data,并跟踪dict中到目前为止的最低分数及其每个日期的相关城市:

min_score_of_date = {}
for city, score, date in weather_data:
    if date not in min_score_of_date or score < min_score_of_date.get(date)[1]:
        min_score_of_date[date] = (city, score)

根据您的示例输入,min_score_of_date将变成:

{'2018-11-13 ': ('Davenport', 708.5), '2018-11-14 ': ('Davenport', 506.1)}

这是另一种方法,如果最低温度日期还没有为你过滤。你知道吗

# each date has a tuple of cities and their temperature
conditions = {
    '2018-11-13': (
        ('Carbondale',1875.341),
        ('Davenport', 708.5)
    )
}

# loop through every date
for date, cities in conditions.items():
    # for every date, loop through its values
    # grab its temperateure and add to the list
    # them find the minimun temperature

    # get all tempertures
    tempertures = [_[1] for _ in cities]
    # get minimum temperature
    min_temperture = min(tempertures)

    # loop throught all cities
    for city in cities:
        # if a city matches min_temperature do whats bellow
        if min_temperture in city:
            # city name
            name = city[0]
            # city temperture
            temperture = str(city[1])

            print(
                "The best weather on "\
                + date\
                + "is in "\
                + name + " with a value of "\
                + temperture
            )

相关问题 更多 >