[英]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.