2014-12-18 6 views
0

안녕하세요 저는 목록의 목록을 가져 와서 목록 내의 개별 밴드를 찾아서 모두가 가장 좋아하는 밴드가 있는지 확인해야하는 문제가있었습니다. 그렇다면 사실을 출력해야합니다. 내 코드를 모듈화하는 프로그래밍 방법을 따라야하지만 코드를 얻을 수는 없습니다. 지금까지 제 코드가 있습니다. 당신이 줄 수있는 모든 도움에 감사드립니다. 목록 당신이,지도, 필터 또는 감소와 같은 기능을 가로 지르는 목록 중 하나를 사용할 수 있습니다 통과해야하는 경우일반적인 즐겨 찾기 밴드 파이썬

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)) 

답변

0

당신이 정말로 당신이 당신의 코드를 모듈화하고 있는지, 처음 두 목록에 공통의 요소를 반환하는 함수하게 보여줍니다 뭔가 작성하려는 경우 지금

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'] 
,

참고 :이 질문은 숙제 문제처럼 보였습니다. 따라서 제 코드가 도움이됩니다. 그렇지 않으면 나는 다른 교차로 방법으로 갔다. 여기 다른 응답에서 논의되었다.

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']) 

편집

에서 교차 .

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']) 
+0

나는 그것을 할 수 없다. 맨 위에 주어진리스트는 그대로 있어야한다. – Nota4rizzle

+0

시도 :'bool (reduce (lambda x, y : x.intersection (y), favoriteBandsList의 l에 대해 (l) 설정)) ' – tmr232

+0

목록을 재정의 할 필요가 없습니다. 세트를 만듭니다. 예를 들어'set (favoriteBandLists [0])'을 실행하면 첫 번째 목록을 집합으로 가져올 수 있습니다 –