2016-10-15 4 views
1

새로운 소식 나는 일주일 동안이 문제를 해결하고 있지만 아직 해결책은 찾을 수 없습니다. 누군가가 나를 알아낼 수 있기를 바랍니다.목록에서 항목을 찾는 방법

목록에서 항목을 찾고 목록 항목을 개별적으로 출력하려면 어떻게합니까?

listitems = ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate'] 

어쨌든 영수증 목록에 관련 음식을 계산할 수 있습니까?

지금까지 한 항목에 대한 음식 만 찾을 수있었습니다. 내 코드는 다음과 같습니다 :

또한 계산 된 각 항목의 다른 목록은 비교를위한 것입니다.

eachitems = ['Beer', 'Cake', 'Chocolate', 'Lemon with ci', 'Chicken'] 
+0

과 장소에 설정을 수정할 수 있습니다 대신

result = result | itemlist 

같은 |을 사용하는 보조 노트로

. 내가 케이크가 맥주와 초콜릿과 관련이 있다는 것을 어떻게 알 수 있습니까? – danidee

답변

0

나는 것 개인적으로 정확히 확인 바로 내가 그것을 달성 할 방법을 알고 당신은 당신이 원하는 결과를 얻을 수 있도록 그 값과 같은 관련 항목과 각 항목에 대한 키를 기준으로 사전이 훨씬 쉬울 것 사용 당신이 만든 목록에서만.

원래 코드에서 끝에 "print (combi)", "print (checklist)"및 "print (correlatedlist)"를 추가하면 실제로 원하는 방식으로 추가하지 않는다는 것을 알 수 있습니다.

파이썬 3.5에서
0

:

import itertools 

listOfStrings = ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate'] 
print ('Original list:', listOfStrings) 
print() 

listOfLists = [group.replace (', ', ',') .split (',') for group in listOfStrings] 
print ('Turned into list of lists:', listOfLists) 
print() 

allFoods = set (itertools.chain (*listOfLists)) 
print ('All individual foods:', allFoods) 
print() 

listOfSets = [set (group) for group in listOfLists] 
print ('A list of sets is handy, since sets contain no duplicates:', listOfSets) 
print() 

dictOfFoods = dict ([[food, set()] for food in allFoods]) 
print ('Prepare a dictionary, where we can put the associated foods:', dictOfFoods) 
print() 

for food in dictOfFoods: 
    for foodSet in listOfSets: 
     if food in foodSet: 
      dictOfFoods [food] .update (foodSet) 
    dictOfFoods [food] .remove (food) 
print ('The dictionary is now filled:', dictOfFoods) 
print() 

for food in dictOfFoods: 
    print ('People who buy', food, 'also buy:') 
    for otherFood in dictOfFoods [food]: 
     print (otherFood) 
    print() 

인쇄됩니다

Original list: ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate'] 

Turned into list of lists: [['Beer', 'Chicken'], ['Cake', 'Chocolate'], ['Lemon with ci', 'Chicken'], ['Beer', 'Beer', 'Cake', 'Chocolate']] 

All individual foods: {'Chocolate', 'Lemon with ci', 'Chicken', 'Cake', 'Beer'} 

A list of sets is handy, since sets contain no duplicates: [{'Chicken', 'Beer'}, {'Chocolate', 'Cake'}, {'Chicken', 'Lemon with ci'}, {'Chocolate', 'Cake', 'Beer'}] 

Prepare a dictionary, where we can put the associated foods: {'Chocolate': set(), 'Lemon with ci': set(), 'Cake': set(), 'Beer': set(), 'Chicken': set()} 

The dictionary is now filled: {'Chocolate': {'Cake', 'Beer'}, 'Lemon with ci': {'Chicken'}, 'Cake': {'Chocolate', 'Beer'}, 'Beer': {'Chocolate', 'Chicken', 'Cake'}, 'Chicken': {'Lemon with ci', 'Beer'}} 

People who buy Chocolate also buy: 
Cake 
Beer 

People who buy Lemon with ci also buy: 
Chicken 

People who buy Cake also buy: 
Chocolate 
Beer 

People who buy Beer also buy: 
Chocolate 
Chicken 
Cake 

People who buy Chicken also buy: 
Lemon with ci 
Beer 

당신은 모든 요소를 ​​통과 할, 당신은 또한 루프에서 루프를 만들 수 있습니다 * itertools을 사용하지 않으려면 listOfLists의 모든 항목을 allFood에 추가하십시오. 처음에는 비어있게됩니다.

0

내가 원했던 것을 정확하게 이해하는 데 언젠가는 걸렸지 만 이것이 효과적인 해결책입니다.

listitems = ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate'] 
eachitems = ['Beer', 'Cake', 'Chocolate', 'Lemon with ci', 'Chicken'] 

for item in eachitems: 
    assoc = [associated for associated in listitems if item in associated] 
    result = set() 
    for itemlist in assoc: 
     itemlist = itemlist.replace(', ', ',').split(',') 
     itemlist = set(itemlist) 

     itemlist.remove(item) 

     result = result | itemlist 
    print('People who buy {} also buy: '.format(item), ', '.join(sorted(result))) 

출력

People who buy Beer also buy: Cake, Chicken, Chocolate 
People who buy Cake also buy: Beer, Chocolate 
People who buy Chocolate also buy: Beer, Cake 
People who buy Lemon with ci also buy: Chicken 
People who buy Chicken also buy: Beer, Lemon with ci 

그들은이 솔루션의 핵심 부분은 중복 항목과 | (노동 조합) 연산자를 제거하는 Sets의 사용이다. 당신이 관련 될 두 식품에 대한 기준을 무엇

result.update(itemlist) 
+0

@E M 피드백이 있으십니까? – danidee