【问题标题】:a problem with using a function and parameters to create a dictionary使用函数和参数创建字典的问题
【发布时间】:2021-12-29 16:12:21
【问题描述】:

我可以使用一些帮助来解决这个问题。我需要创建一个函数来创建一个带有 4 个参数的字典和一个增加该字典每个条目的键。到目前为止,我有这个:

def create_db(temp, rain, humidity, wind):
    weather = {}
    n = 0
    for i in (temp, rain, humidity, wind):
        n = n + 1
        weather[n] = (temp, rain, humidity, wind)
    return weather

temp = [1, 5, 3]
rain = [0, 30, 100]
humidity = [30, 50, 65]
wind = [3, 5, 7]
weather = create_db(temp, rain, humidity, wind)
print(weather)

这段代码的问题在于它会打印:

{1: (1, 0, 30, 3), 2: (1, 0, 30, 3), 3: (1, 0, 30, 3), 4: (1, 0, 30, 3)}

它只为它们放入列表的第一个值。 我做错了什么?

【问题讨论】:

    标签: python function dictionary


    【解决方案1】:

    我会指出,虽然您的方法没有“错误”(在应用修复后),但更 Pythonic 的方式无需完全使用索引:

    def create_db(temp, rain, humidity, wind):
        return {n: vals for n, vals in enumerate(zip(temp, rain, humidity, wind), 1)}
    

    或者更精简的版本:

    def create_db(temp, rain, humidity, wind):
        return dict(enumerate(zip(temp, rain, humidity, wind), 1))
    

    【讨论】:

    • 你甚至不需要字典理解; dict(enumerate(...)) 就足够了。
    • @chepner 是的,谢谢!添加了替代品,但保留了原件以显示一些具体细节。
    【解决方案2】:

    temp、rain 等都是列表。您需要引用每个列表中的元素 - 即

    weather[n] = (temp[n], rain[n], humidity[n], wind[n])
    

    您也不是指for i in (temp, rain, humidity, wind) - 这将是 4,因为那里有 4 个列表变量。而是使用其中一个列表的长度,例如:

    for n in range(len(temp)):
    

    这样你也不需要增加n

    【讨论】:

    • for n in range(len(temp))
    • 谢谢 - 已修复。我通常会花大部分时间告诉人们“不要”使用 for i in range(len(x))x[i],而他们只是想要列表中的元素,所以显然我的大脑拒绝在这里输入它!
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2021-02-03
    • 2015-07-05
    • 2020-07-30
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多