【发布时间】:2021-01-17 01:43:44
【问题描述】:
我正在尝试让我的代码更“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 程序员,我也希望能解释一下可能的解决方案,以便我可以继续学习。
【问题讨论】:
-
这里已经回答了这个问题:stackoverflow.com/questions/701802/…
-
如果还没有完成,您应该通过Python tutorial 处理。它提供了如何使用字典的示例以及“范围”功能以及更多有用的内容。
标签: python function loops dictionary