如何通过列表组件做出命令-python

时间:2018-11-12 19:45:17

标签: python python-3.x

我有一个日期列表:

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 ')]
weather_data中的

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

基本上,如果我有一个以日期为键且(city,value)为值的字典,则可以轻松地找到每天城市中的最低值。

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

使用字典甚至是实现此目的的好方法吗?

2 个答案:

答案 0 :(得分:2)

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

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)}

答案 1 :(得分: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
            )