我必须创建一个列表列表代码,它返回" True"确切地说,当所有列表中存在(至少1个)和喜欢的乐队时(可能> 3)。我对编程非常陌生,我很遗憾该怎么做。我尝试了一些东西,但它没有完全填满。我需要一些帮助!
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
答案 0 :(得分: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!
(顺便说一句,函数和变量名在Python中传统上用snake_case编写,而不是camelCase)
答案 1 :(得分:0)
您可以使用:
s=set(favorite_band_lists[0])
for ii in favorite_band_lists[1:]:
s=s.intersection(s,ii)
if len(s) == 0:
break
一旦交叉路口为空,这将停止,这可能是理想的。它还返回列表中通用的波段(如果有)。要生成True
或False
,请检查s的长度 - 交叉点列表 - 是否为> 0
print len(s) > 0
答案 2 :(得分: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。