[英]How do I make this into a for loop?
所以基本上我正在尝试替换为:
board = {
0:[0, 1, 2, 9, 10, 11, 18, 19, 20],
1:[3, 4, 5, 12, 13, 14, 21, 22, 23],
2:[6, 7, 8, 15, 16, 17, 24, 25, 26]}
使用for循环将自动创建它。 抱歉,如果这看起来很明显,但是我有点菜鸟了,对此我遇到了很多麻烦。
看起来您正在生成前27个整数(从0开始),然后对其进行分组。 让我们这样写吧。
def group_by_threes(n=27, group_count=3):
# The end result will be a dict of lists. The number of lists
# is determined by `group_count`.
result = {}
for x in range(group_count):
result[x] = []
# Since we're using subgroups of 3, we iterate by threes:
for x in range(n // 3):
base = 3 * x
result[x % 3] += [base, base + 1, base + 2]
# And give back the answer!
return result
通过将组的大小(在这种情况下为3)作为参数可以使此代码更好,但是我将其留给读者练习。 ;)
这种方法的优点是,与编写一次性生成您要查找的精确列表的一次性方法相比,它更具模块化和适应性。 毕竟,如果您只想生成您显示的那个列表,那么最好对其进行硬编码!
def create_list(x):
a = [x,x+1,x+2,x+9,x+9+1,x+9+2,x+18,x+18+1,x+18+2]
return a
output = {}
for i in range(3):
output[i*3] = create_list(i*3)
print output
请尝试这个,您将获得所需的输出
def create_list(x):
res = []
for i in xrange(0,3):
for j in xrange(0,3):
res.append(3*x+ 9*i + j)
return res
dictionary={}
for i in xrange(0,3):
dictionary[i]=create_list(i)
print dictionary
结果:
{0: [0, 1, 2, 9, 10, 11, 18, 19, 20], 1: [3, 4, 5, 12, 13, 14, 21, 22, 23], 2: [6, 7, 8, 15, 16, 17, 24, 25, 26]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.