2014-09-04 109 views
-1

我正在處理一個嵌套列表。我正在使用for循環來遍歷它。有時列表中的特定項目依賴於後續的嵌套列表。我嘗試了迭代並使用next,但是耗盡了我尚未訪問的項目。這是我的清單。當我查看第一個嵌套列表時,如果後續列表中包含引用蘋果的數據並說它是「bad_apple」,我不想打印它。可能會有未來的嵌套列表,後面跟着「good_apple」,我想打印那個。python:我如何訪問嵌套列表中的後續列表

fruit = [ 
    ["apple", "round", "small", "red"], 
    ["banana", "long", "large", "yellow"], 
    ["apple", "round", "large", "bad_apple"] 
    ["apple", "round", "medium", "red"], 
    ["banana", "long", "large", "yellow"], 
    ["apple", "round", "large", "good_apple"] 
] 

for i in fruit: 
    # print i only if there is no "bad_apple" in the following 3 nested lists 
    print i 

因此,在這個例子中,我不希望打印第一的蘋果,「小」之一,但因爲它後面是後續我會想打印第二的蘋果,「中等」一個列表中包含「good_apple」的列表。我只想看到2或3個嵌套列表進入「未來」。

+2

不是很清楚你在問什麼。我認爲你需要發佈一個更完整的例子 – Cfreak 2014-09-04 21:29:56

+0

後來你是指下一個列表或任何以下列表? – 2014-09-04 21:30:12

+0

您的示例需要輸出什麼? – 2014-09-04 21:30:46

回答

0

如果希望非特異性值當前元素後檢查任何後續列表使用enumerate

​​
0

fruit[0][1]會給'round'

fruit[1][2]會給'long'

這樣的循環中,您可以嘗試像

for i in fruit: 
    for j in i: 
     print j 

不知道語法,但它幾乎接近

1

是這樣的:

採用0

列表爲例:

fruit = [ 
    ["apple", "round", "large", "red"], 
    ["banana", "long", "large", "yellow"], 
    [ "apple", "round", "large", "bad_apple"] 
] 

其中["apple", "round", "large", "red"]是第一子列表

你可以使用:

for list in fruit: 
    for item in list: 
     print(item) 

在其他一些情況下也可以使用這個有用形式:

print(fruit[1][3]) 

這裏這個將打印在第二子列表(記住索引從0開始的第一個項目在列表中)

詹姆斯第4項

+0

這如何訪問後續列表? – 2014-09-04 21:53:05

0

你將要做的名單,如果你上了雙套迭代想爲你分析每個元素未來信息(除非您打算使用空間記憶的東西,你走。)

for i in range(len(fruit)): 
    badFruit = False 
    for j in range(len(fruit)): 
     for attribute in fruit[j]: 
      if "bad_" + fruit[i] == attribute: 
       badFruit = True 
       break 
     if badFruit: 
      break 
    else: 
     print(fruit[i]) 

這是許多可能的解決方案之一。

0

除了樂於助人的發電機功能,代碼是不是太糟糕。

for before, i, after in partitions(fruit): 
    if not any(j[0] == i[0] and 'bad_'+i[0] == j[3] for j in after[:3]): 
    print i 

正如可以看到的,partitions()函數返回的每個元素在列表中,與它的前面和後面的元件一起。然後由循環體來確定bad_apple條件。

下面是完整的程序:

def partitions(l): 
    preceding = [] 
    subsequent = l[:] 
    while subsequent: 
     current = subsequent.pop(0) 
     yield preceding, current, subsequent 
     preceding.append(current) 

fruit = [ 
    ["apple", "round", "small", "red"], 
    ["banana", "long", "large", "yellow"], 
    ["apple", "round", "large", "bad_apple"], 
    ["apple", "round", "medium", "red"], 
    ["banana", "long", "large", "yellow"], 
    ["apple", "round", "large", "good_apple"] 
] 

for before, i, after in partitions(fruit): 
    if not any(j[0] == i[0] and 'bad_'+i[0] == j[3] for j in after[:3]): 
    print i