循环浏览功能并自动生成字典

问题描述

我正在尝试使代码更具“ Pythonic”性。

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

        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,并自动生成字典和键+值。

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

        index = 1
        for i in range(16):
            index += 12
            getIndividualCounts(42) + index
            return ({'c' + str(i) + ':'+ c + i} )

不用说这是行不通的。我尝试了多次迭代,但是找不到任何可行的方法。作为一个相对较新的Python程序员,我也希望对可能的解决方案做出解释,以便我可以继续学习。

解决方法

这是一个可能的解决方案

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

不要使用这些中间变量,只需直接构建字典即可:

using (MySqlCommand cmd = new MySqlCommand("insert into table_name(username)values(@username)",conn))
{                                                              
   cmd.Parameters.AddWithValue("@username",username);
   cmd.ExecuteNonQuery();
}

或具有dict理解:

main_data = {}

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

请注意,更笼统地说,如果您觉得需要一些相关变量,就像在代码的第一部分中所做的那样,则应使用列表或字典将它们放入结构中,而不仅仅是拥有独立变量与他们的名字有关。

,

带有说明的代码:

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

打印:

{'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}
,
main_data = {}
for counter,val in enumerate(range(42,222+1,12)):
    main_data[f'c{counter+1}'] = getIndividualCounts(val)

这将满足您的需求。 f''是指格式字符串。因此,您可以通过将变量放入{}

来在字符串中插入变量