2014-12-11 153 views
0

當所有列表中存在(至少1個)和最喜歡的樂隊(可能> 3)時,我必須創建一個列表清單的代碼,其中它返回「True」。我對編程非常陌生,而且我很遺憾要做什麼。我嘗試了一些東西,但沒有完全填充,我需要一些幫助!Python-列表列表

favoriteBandLists = [ 
    ["Metallica","Linkin Park","Alice In Chains","Nirvana", "Soundgarden"], 
    ["Pink Floyd","Alice In Chains","Soundgarden","Metallica","Linkin Park"], 
    ["Audioslave","Offspring","Soundgarden","Linkin Park","The Beatles"]] 

我的代碼:

def commonFavoriteBand(list): 
    foundCounterExampleyet = False 
    for i in range(()): 
     if(()): 
      foundCounterExampleYet = True 
    return not(foundCounterExampleYet) 

print (commonFavoriteBand()) 

def commonFavoriteBandA(): 
    foundExampleYet = False 
    for value in values: 
     if(): 
      foundExampleYet = True 

return foundExampleYet 
+1

你能仔細檢查你的發佈代碼的縮進嗎?很難看到那裏發生了什麼.. – msturdy 2014-12-11 03:11:47

+0

@msturdy是否有縮進的具體方法?我很抱歉我在這裏有一種新的 – 2014-12-11 03:18:16

+0

複製你的代碼到框中,選擇它,然後按Ctrl + k – msturdy 2014-12-11 03:21:40

回答

1

我想說的最簡單的,但大多數理解的方式是這樣的:

favorite_band_lists = [ 
    ["Metallica", "Linkin Park", "Alice In Chains", "Nirvana", "Soundgarden"], 
    ["Pink Floyd", "Alice In Chains", "Soundgarden", "Metallica", "Linkin Park"], 
    ["Audioslave", "Offspring", "Soundgarden", "Linkin Park", "The Beatles"], 
] 

def common_favorite_band(band_lists): 
    # If there are no bands at all, you can't really say there are any in 
    # common 
    if not band_lists: 
     return False 

    # Convert the first band list to a "set" -- a group of unique items 
    common_bands = set(band_lists[0]) 

    # Then, for every other band list... 
    for bands in band_lists[1:]: 
     # ...intersect it with the running set. This means `common_bands` 
     # should throw away anything that isn't also in `bands`. 
     common_bands.intersection_update(bands) 

    # Now common_bands contains only the bands that are in every list. 
    # But you wanted True or False, so cast it to a bool -- an empty set 
    # will become False, a set with at least one item will become True. 
    return bool(common_bands) 

print(common_favorite_band(favorite_band_lists)) # True! 

(順便說一句,函數和變量名傳統上被寫在snake_case在Python,不是camelCase)

+0

當我運行它,它說「band_lists」沒有定義? – 2014-12-12 02:52:02

+0

你犯了一個錯字嗎?它對我來說運行良好 – Eevee 2014-12-12 20:41:19

0

你可以用這個:

s=set(favorite_band_lists[0]) 
for ii in favorite_band_lists[1:]: 
    s=s.intersection(s,ii) 
    if len(s) == 0: 
     break 

一旦交點爲空,這可能會停止,這可能是可取的。它還返回列表中共有的頻段,如果有的話。爲了生產TrueFalse,檢查s的長度 - 的交匯列表 - > 0

print len(s) > 0 
0

這裏有不同的解決方案給了別人:

def common_favorite_band(band_lists): 
    for band in band_lists[0]: 
     count = 0 
     for band_list in band_lists[1:]: 
      if band not in band_list: 
       break 
      else: 
       count += 1 
     if count == len(band_lists) - 1: 
      return True 
    return False 

它着眼於一切第一個列表中的樂隊,並檢查該樂隊是否在每個其他列表中。我們每次加1來計數。對於任何樂隊,如果count達到band_lists - 1的長度,那麼我們可以返回True並完成。如果任何時候一個樂隊沒有出現在另一個列表中,我們會從該循環的迭代中斷開並嘗試另一個樂隊。如果我們檢查了每個樂隊,並且我們沒有計算出band_list_1的長度,那麼我們返回False。