在列表中搜索相似元素

2024-07-07 07:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张桌子,里面有:

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循环来打印,所以我会很感激在这方面的帮助。你知道吗


Tags: 函数字符串元素tablespacefour桌子while
3条回答

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]}

这里有一个使用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}}

您可以使用字典获取从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]}

相关问题 更多 >