Python:返回两个或多个列表共有的项目

Python: Returning items common to two or more lists

我是初学者,请多多包涵!我有一大段代码:

def friendslike(network,user):
    friends=[]
    friendgames=[]
    friends+=get_connections(network,user)
    for user in friends:
        friendgames.append(get_games_liked(network,user))
    return friendgames

这个returns:

[['Seahorse Adventures', 'Ninja Hamsters', 'Super Mushroom Man'], ['Call of Arms', 'Dwarves and Swords'], ['City Comptroller: The Fiscal Dilemma', 'Super Mushroom Man']]

我想做的是return出现在两个或多个列表中的游戏名称。我不确定如何解决这个问题 - 是拆分列表,还是某种交叉查询。

正如我所说,我是 Python 的新手,一般来说是编码方面的新手。感谢任何指点 - 即使它只是告诉我要研究什么。

既然你想要两个或更多朋友喜欢的游戏,我建议统计每个游戏出现的次数,然后返回那些出现超过一次的。您可以使用 collections.Counter 轻松进行计数:

import collections

def friendslike(network,user):
    games = collections.Counter()
    for friend in get_connections(network, user):
        games.update(get_games_liked(network, friend))
    return [game for game, count in games.items() if count >= 2]

您应该在合并所有子列表后使用出现次数来过滤您的数组。希望这个例子对你有所帮助:

from itertools import chain
friendgames = [['Seahorse Adventures', 'Ninja Hamsters', 'Super Mushroom Man'],
        ['Call of Arms', 'Dwarves and Swords'],
        ['City Comptroller: The Fiscal Dilemma', 'Super Mushroom Man']]
g = list(chain.from_iterable(friendgames))
rez=set([x for x in g if g.count(x)>1]) # more than 1 occurrence
print(rez)
# {'Super Mushroom Man'}

我会使用 collections.Counter。它是一个类似 dict 的结构,可以计算你给它的东西。这就像 dict.

的自动计数功能
import collections
friendgames = [['Seahorse Adventures', 'Ninja Hamsters', 'Super Mushroom  Man'],
        ['Call of Arms', 'Dwarves and Swords'],
        ['City Comptroller: The Fiscal Dilemma', 'Super Mushroom Man']]
c = collections.Counter(b for a in friendgames for b in a)
print [a for a,b in c.items() if b >= 2]

这会打印至少出现两次的唯一条目,即:

['Super Mushroom Man']

您可以使用

gameSet = set()
set([g for games in gamesList for g in games if g in gameSet or gameSet.add(g)])

榜单只会记录return Trueif g in gameSet 的游戏;如果他们至少被添加到集合中一次,他们被添加到最终列表中。

是的,欢迎!这里有一些选项可以尝试:)

#intersect options
jim = ['Seahorse Adventures', 'Ninja Hamsters', 'Super Mushroom Man']
bob = ['Call of Arms', 'Dwarves and Swords']
tom = ['City Comptroller: The Fiscal Dilemma', 'Super Mushroom Man']

#meathod 1
for j in jim:
    if j in tom:
        print j

#meathod 2, with dictionary
gamers = {'jim':jim
            ,'bob':bob
            ,'tom':tom
            }
games = {}
for g in gamers.keys():
    for game in gamers[g]:
        if game not in games.keys():
            games[game] = [g]
        else:
            games[game].append(g)
for g in games.keys():
    if games[g][1:]:
        print g, games[g]

我发现如果信息存储在某个地方,字典会很有用,因为在我看来,它更容易追加并且包含更多信息。如果您开始使用大列表或必须经常执行此操作,则迭代方法在计算上也有些昂贵。但作为开始,我希望它能有所帮助。