2016-09-21 23 views
-1

也許標題似乎很奇怪,但我bloqued某些時段進行搜尋如何創建這種情況的循環:如何在python中爲這種情況創建一個for循環?

我有這種格式列表的列表:

data=[['nature', author1, author2, ...author n] 
     ['sport', author1, author2, ....author n] 
     .... 
     ] 

我有嘗試這種代碼:

 authors=[author1, author2, ...author n] 
     for i in range(len(authors)): 

     data = [['nature', function(names[i], 'nature')], 
       ['sport', function(names[i], 'sport') 
      ..] 

但不幸的是我想它返回以下格式的結果:

data=[['nature', author1] 
     ['sport', author1] 
     .... 
     ] 
+0

你能更清楚你的慾望輸出是什麼嗎? – MooingRawr

+0

我的願望輸出是fisrt代碼,但有一個for循環 –

+0

給我幾分鐘我會給你一個工作代碼的例子。我不明白你面臨的挑戰是什麼。也許我的代碼將清除它。你有什麼Python版本?我在3.5上只是想確保我的代碼在你的結尾工作。 –

回答

0
ary_grp_Example = [["AA1", "BB1"], ["CC2", "DD2"],["EE3","FF3"]] ### Dimension as a three column matrix array (list) 
ary_grp_Example.pop(0) ## Kill the first record leaving two 

#Loop through by row (x) 
for int_CurCount in range(0,len(ary_grp_Example)): 
     print ("Row: " + str(int_CurCount) 
      + " was #" 
      + str(ary_grp_Example[int_CurCount][0]) 
      + "#" + str(ary_grp_Example[int_CurCount][1]) 
      +"#") 

#Loop through by Cell (x,y) 
for int_RowCount in range(0,len(ary_grp_Example)): 
    for int_ColCount in range(0,len(ary_grp_Example[int_RowCount])): 
     print ("Cell Data for location =(" 
      + str(int_RowCount) + "," 
      + str(int_ColCount) + ") was #" 
      + ary_grp_Example[int_RowCount][int_ColCount] 
      + "#") 

如果您使用兩個數字數據[1] [1]或數據[1] [2],則可以獲取數據。有時稱爲矩陣數組或矩陣列表。 Pythons的名稱似乎是一個「列表」,但它是一個多維列表,又名矩陣數組/列表。

體育作者2例如將數據[1] [2],因爲這些是基於零的計數。

要遍歷所有數據,您必須循環逐行讀取數據庫結果集。

+0

當我試圖將數據聲明爲矩陣時,它向我展示了由紅色加下劃線的數據。'data [i] [j] = ..' –

+0

嘗試運行我的代碼,確保它可以正常工作爲您的Python版本。然後將我的數據更改爲您的數據。看看它是否仍然有效。讓我知道,如果那是你想要做的。 –

0

是你想要的東西沿着這些線?

>>> data=[['nature', 'author1', 'author2', 'author3'],['sport', 'author1', 'author2', 'author3'],['Horses', 'author1', 'author2']] 
>>> for i in range(len(data)): 
     for x in range(1, len(data[i])): 
      print data[i][0], data[i][x] 
nature author1 
nature author2 
nature author3 
sport author1 
sport author2 
sport author3 
Horses author1 
Horses author2 
0

將其轉換爲一個字典,然後遍歷該密鑰對

data = [['foo', 1, 2, 3], ['bar', 2,3,4]] 
dat = {i[0]: i[1:] for i in data }   
for k, v in dat.items(): 
    print("{0}: {1}".format(k, v)) 


Output 
bar: [2, 3, 4] 
foo: [1, 2, 3] 

除了.... 不這樣做

我只是顯示這個來顯示你的數據應該放在字典中。

+0

我通常總是使用矩陣數組/多維列表。你建議的「字典」有什麼更好的? –

+0

@mthead - 我甚至不確定問題是什麼。我很快可能會刪除我的答案,但如果內部數組中的第一項始終是鍵,那麼您應該使用爲鍵值設計的數據結構。 – Sayse

相關問題