常见的乐队Python

时间:2014-12-18 17:02:46

标签: python list modularization

你好我遇到了一个问题,我不得不拿一份列表并在这些列表中找到各个乐队,看看他们是否都有一个共同喜欢的乐队。如果是这样我应该输出true。我需要遵循这种编程方法,我模块化我的代码,但我似乎无法得到它。到目前为止,这是我的代码。感谢您提供的所有帮助。

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

def commonFavoriteBand(favoriteBandLists):

    thereExists= False
    for i in (favoriteBandLists[2]):
        if(commonFavoriteBandA(favoriteBandLists)):
            thereExists = True
    return (thereExists)

def commonFavoriteBandA(favoriteBandLists):

    foundCounterExampleYet = False
    for band in favoriteBandLists[2]:
        if not(band == favoriteBandLists[0:1]):
            foundCounterExampleYet = True
    return not foundCounterExampleYet

print(commonFavoriteBand(favoriteBandLists))

2 个答案:

答案 0 :(得分:1)

使用set对象的交叉

set(["Metallica","Linkin Park","Alice In Chains","Nirvana", "Soundgarden"]).intersection(["Pink Floyd","Alice In Chains","Soundgarden","Metallica","Linkin Park"])
set(['Linkin Park', 'Alice In Chains', 'Soundgarden', 'Metallica'])

修改

如果需要遍历列表,您可以使用任何列表遍历函数,例如map,filter或reduce。

favoriteBandLists = [["Metallica","Linkin Park","Alice In Chains","Nirvana", "Soundgarden"],
    ["Pink Floyd","Alice In Chains","Soundgarden","Metallica","Linkin Park"],
    ["Audioslave","Offspring","The Beatles", "Soundgarden"]]
reduce(lambda a, b: a.intersection(b), (set(a) for a in favoriteBandLists))
set(['Soundgarden'])

答案 1 :(得分:0)

如果你真的想写一些表明你正在模块化代码的东西,首先要创建一个函数,在两个列表中返回common元素:

def commonBand(L1, L2):
    answer = []
    for band in L1:
        if band in L2:
            answer.append(band)
    return answer

现在,多次调用该函数:

def main(listOfLists):
    i = 1
    answer = listOfLists[0]
    while i<len(listOfLists):
        answer = commonBand(answer, listOfLists[i])
        if not answer:
            break
        i += 1
    return answer

输出:

In [193]: main(favoriteBandLists)
Out[193]: ['Soundgarden']

注意:这对我来说似乎是一个功课问题,所以我的代码有助于此。否则我会使用已经在其他响应中讨论过的交集方法