1

我一直在研究这个问题,似乎很长一段时间。我有一本看起来像这样的字典:

{'1': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,'The Night Listener': 3.0}, '2': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,'You, Me and Dupree': 3.5},'3': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,'Superman Returns': 3.5, 'The Night Listener': 4.0}}

实际上事情要大得多,但我想要找到的是列表或集合,其中包含至少有 2 部电影彼此相同的一对 id。但肯定有什么问题,因为第一把钥匙必须和第二把钥匙核对,然后用第一把钥匙和第三把钥匙核对,直到钥匙用完,然后用第二把钥匙和第三把钥匙核对,以此类推,直到我没有更多的钥匙。然后轮到第三把钥匙了。

最后,我只想获得至少有 2 部电影共有的键。

我试过这样做:

def sim_critics(movies):
    similarRaters=set()

    first=1
    lastCritic= ''

    movie_over = collections.defaultdict(list)
    movCount=Counter(movie  for v in movies.values() for movie in v)

    for num in movies:
        for movie, _ in movies[num].items():
            movie_over[movie].append(num)


    for critic,_ in movie_over.items():
        if first!=1:
            critic_List = collections.Counter(movie_over[critic])
            critic2_list = collections.Counter(movie_over[lastCritic])
            overlap = list((critic_List & critic2_list).elements())

            if len(overlap) >= 2:
                key = critic + " and " + lastCritic 
                similarRaters.add(key)  
        lastCritic= critic
        first=2  
    return similarRaters
4

1 回答 1

1

一个简单的解决方案是这样做:

def simCritics(movies):
    matchingDicts = set()
    for m in movies:
        for i in movies:
            if (len(m) + len(i)) > len(set(m).union(i)):
                matchingDicts.add((m, i))

    myList = [i for i in list(matchingDicts) if i[0] != i[1]]

    myL = []
    for i in myList:
        if (i[1], i[0]) in myL:
            continue
        myL.append(i) 
    return myL

中间的比较(比较 len)是至关重要的,因为如果电影重叠,它们将至少有一个相同的键,所以并集(删除重复项)将小于总和。

于 2013-05-03T22:54:33.283 回答