首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从列表组件中生成dict - python

如何从列表组件中生成dict - python
EN

Stack Overflow用户
提问于 2018-11-12 19:45:16
回答 2查看 80关注 0票数 2

我有一份日期清单:

代码语言:javascript
复制
dates = ['2018-11-13 ', '2018-11-14 ']

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

代码语言:javascript
复制
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 ')]

i1 in weather_data是一个基于每天气候信息的气候评分。为了这个例子,我缩短了上面的列表。

,我的目标是找到每天气候得分最低的城市,。我认为一个很好的方法是把它们放在字典里。

我想要的一个例子是..。

代码语言:javascript
复制
conditions_dict = {'2018-11-13': ('Carbondale',1875.341), ('Davenport', 708.5)}

我的最终输出将是..。

代码语言:javascript
复制
The best weather on 2018-11-13 is in Davenport with a value of 708.5

基本上,如果我有一个以日期为键,以( city,value)为值的数据,那么我就可以轻松地找到每天按城市计算的最低值。

然而,我不知道如何使我的字典看起来像这样。我真正挣扎的部分是如何在一天内将日期与多个城市的读数相匹配。

用字典是做这件事的好方法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-12 20:00:04

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

代码语言:javascript
复制
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将变成:

代码语言:javascript
复制
{'2018-11-13 ': ('Davenport', 708.5), '2018-11-14 ': ('Davenport', 506.1)}
票数 2
EN

Stack Overflow用户

发布于 2018-11-12 20:35:42

这是另一种方法,你可以这样做,如果最低气温日期还没有为你过滤。

代码语言:javascript
复制
# 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
            )
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53269072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档