:
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에 추가하십시오. 처음에는 비어있게됩니다.
과 장소에 설정을 수정할 수 있습니다 대신
같은
. 내가 케이크가 맥주와 초콜릿과 관련이 있다는 것을 어떻게 알 수 있습니까? – danidee|
을 사용하는 보조 노트로