我有一张包含以下内容的表:
table = [[1, 'FANTASTIC FOUR', 'EXOTIC SPACE'],[4, 'CRIMSON PEAK', 'MINIONS','SUPERMAN'],[20, 'FANTASTIC FOUR', 'EXOTIC SPACE']]
我正在编写一个python函数来遍历表格,查找字符串元素中的相似之处并以格式打印出来:
Movie: FANTASTIC FOUR, EXOTIC SPACE
UserID: 1,20 #since user 1 and user 20 both watch exactly the same movie
我试过写作:
i = 0
while i<len(table)-1:
g = table[i][1:]
if g == table[i+1][1:]:
print(table[i][0],table[i+1][0])
i+=1
但它的效果不佳。我并不擅长使用while循环进行打印,所以我会对此有所帮助。
答案 0 :(得分:1)
Python中的循环通常不会非常使用i
。试试这个:
table = [[1, 'FANTASTIC FOUR', 'EXOTIC SPACE'],[4, 'CRIMSON PEAK', 'MINIONS','SUPERMAN'],[20, 'FANTASTIC FOUR', 'EXOTIC SPACE']]
watcher = {}
for x in table:
for movie in x[1:]:
watcher_for_movie = watcher.get(movie, [])
watcher_for_movie.append(x[0])
watcher[movie] = watcher_for_movie
print(watcher)
输出:
{'EXOTIC SPACE': [1, 20], 'CRIMSON PEAK': [4], 'MINIONS': [4], 'SUPERMAN': [4], 'FANTASTIC FOUR': [1, 20]}
答案 1 :(得分:1)
以下是使用itertool.combinations
和词典的一种解决方案。
对于字典键使用集合或frozensets是最佳选择,因为无论您是查找(1, 20)
还是(20, 1)
,都希望获得相同的结果。
from itertools import combinations
table = [[1, 'FANTASTIC FOUR', 'EXOTIC SPACE'],
[4, 'CRIMSON PEAK', 'MINIONS','SUPERMAN'],
[20, 'FANTASTIC FOUR', 'EXOTIC SPACE']]
d = {k: set(v) for k, *v in table}
common = {frozenset((i, j)): d[i] & d[j] for i, j in \
combinations(d, 2) if d[i] & d[j]}
# {frozenset({1, 20}): {'EXOTIC SPACE', 'FANTASTIC FOUR'}}
扭转这种映射也是微不足道的:
common_movies = {frozenset(v): set(k) for k, v in common.items()}
# {frozenset({'EXOTIC SPACE', 'FANTASTIC FOUR'}): {1, 20}}
答案 2 :(得分:1)
您可以使用词典来吸引观看同一部电影的用户table
table = [[1, 'FANTASTIC FOUR', 'EXOTIC SPACE'],[4, 'CRIMSON PEAK', 'MINIONS','SUPERMAN'],[20, 'FANTASTIC FOUR', 'EXOTIC SPACE']]
movie_user_mapping = dict() # Create an empty dictionary
# Iterate over every item in table
for item in table:
# Loop over the movies i.e excluding the first element
for movie in item[1:]:
# Check if movie is present as key in the dictionary, if not create a new key with the movie name and assign it an empty list
if movie not in movie_user_mapping:
movie_user_mapping[movie] = []
# Check if user is already added to the list for the movie, if not add the user
if item[0] not in movie_user_mapping[movie]:
movie_user_mapping[movie].append(item[0])
# Print the result
print(movie_user_mapping)
输出:
{'FANTASTIC FOUR': [1, 20], 'EXOTIC SPACE': [1, 20], 'CRIMSON PEAK': [4], 'MINIONS': [4], 'SUPERMAN': [4]}