2014-12-11 123 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。