我正在努力使我的代码更“毕多尼”。
目前我正在调用一个函数16次,每次递增12次。然后,我将这些变量添加到字典中,并分配一个与变量(Value)同名的键:
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程序员,我也希望能够解释一下可能的解决方案,这样我就可以学习向前迈进了。
发布于 2020-10-01 10:46:03
这是一个可能的解决方案。
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)发布于 2020-10-01 10:44:19
不要使用这些中间变量,只需直接构建dict:
main_data = {}
for index in range(1, 17):
main_data['c' + str(index)] = getIndividualCounts(30 + 12*index)或者带着一种白痴的理解力:
main_data = {'c' + str(index): getIndividualCounts(30 + 12*index) for index in range(1, 17)}请注意,更普遍地说,如果您觉得需要有一些相关变量,就像您在代码的第一部分中所做的那样,您应该使用一个列表或一个dict将它们放在一个结构中,而不是只与它们的名称相关的独立变量。
发布于 2020-10-01 10:44:49
附有解释的守则:
# 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}https://stackoverflow.com/questions/64153611
复制相似问题