首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环函数和自动生成字典

循环函数和自动生成字典
EN

Stack Overflow用户
提问于 2020-10-01 10:35:17
回答 4查看 45关注 0票数 0

我正在努力使我的代码更“毕多尼”。

目前我正在调用一个函数16次,每次递增12次。然后,我将这些变量添加到字典中,并分配一个与变量(Value)同名的键:

代码语言:javascript
复制
        c1 = getIndividualCounts(42)
        c2 = getIndividualCounts(54)
        c3 = getIndividualCounts(66)
        c4 = getIndividualCounts(78)
        c5 = getIndividualCounts(90)
        c6 = getIndividualCounts(102)
        c7 = getIndividualCounts(114)
        c8 = getIndividualCounts(126)
        c9 = getIndividualCounts(138)
        c10 = getIndividualCounts(150)
        c11 = getIndividualCounts(162)
        c12 = getIndividualCounts(174)
        c13 = getIndividualCounts(186)
        c14 = getIndividualCounts(198)
        c15 = getIndividualCounts(210)
        c16 = getIndividualCounts(222)

        main_data = {'c1':c1, 'c2':c2, 'c3':c3, 'c4':c4, 'c5':c5, 'c6':c6, 'c7':c7, 'c8':c8, 'c9':c9, 'c10':c10, 'c11':c11, 'c12':c12, 'c013':c13, 'c14':c14, 'c15':c15, 'c16':c16} 

这是目前工作良好,但是相当庞大。我想做的是循环通过函数16次,每次增加12开始索引,并自动生成字典和键+值。

到目前为止,这就是我所拥有的:

代码语言:javascript
复制
        index = 1
        for i in range(16):
            index += 12
            getIndividualCounts(42) + index
            return ({'c' + str(i) + ':'+ c + i} )

不用说,它不起作用。我尝试过多次迭代,但找不到有效的方法。作为一个相对较新的Python程序员,我也希望能够解释一下可能的解决方案,这样我就可以学习向前迈进了。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-10-01 10:46:03

这是一个可能的解决方案。

代码语言:javascript
复制
main_data = dict()
inital_value = 42

for i in range(16):
    index = 'c{}'.format(i+1)
    value = inital_value + i*12
    main_data[index] = getIndividualCounts(value)
    print(index, value)
票数 1
EN

Stack Overflow用户

发布于 2020-10-01 10:44:19

不要使用这些中间变量,只需直接构建dict:

代码语言:javascript
复制
main_data = {}

for index in range(1, 17):
    main_data['c' + str(index)] = getIndividualCounts(30 + 12*index)

或者带着一种白痴的理解力:

代码语言:javascript
复制
main_data = {'c' + str(index): getIndividualCounts(30 + 12*index) for index in range(1, 17)}

请注意,更普遍地说,如果您觉得需要有一些相关变量,就像您在代码的第一部分中所做的那样,您应该使用一个列表或一个dict将它们放在一个结构中,而不是只与它们的名称相关的独立变量。

票数 0
EN

Stack Overflow用户

发布于 2020-10-01 10:44:49

附有解释的守则:

代码语言:javascript
复制
# your function you want to call:
def getIndividualCounts(x):
    return x

# the dictionary where you want to store data
main_data = {}

# the loop, i goes from 0, 1, ... to 15
for i in range(16):
    key = 'c{}'.format(i+1)                 # create key (c1, c2, c3, ...)
    value = getIndividualCounts(42 + i*12)  # create value by calling the function (42, 54, ...)

    # store the key, value inside the dictionary
    main_data[key] = value

# print the data:
print(main_data)

指纹:

代码语言:javascript
复制
{'c1': 42, 'c2': 54, 'c3': 66, 'c4': 78, 'c5': 90, 'c6': 102, 'c7': 114, 'c8': 126, 'c9': 138, 'c10': 150, 'c11': 162, 'c12': 174, 'c13': 186, 'c14': 198, 'c15': 210, 'c16': 222}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64153611

复制
相关文章

相似问题

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