我是初学者,所以请耐心等待!我有一大堆代码:
def friendslike(network,user):
friends=[]
friendgames=[]
friends+=get_connections(network,user)
for user in friends:
friendgames.append(get_games_liked(network,user))
return friendgames
返回:
[['Seahorse Adventures', 'Ninja Hamsters', 'Super Mushroom Man'], ['Call of Arms', 'Dwarves and Swords'], ['City Comptroller: The Fiscal Dilemma', 'Super Mushroom Man']]
我想要做的是返回两个或多个列表中出现的游戏名称。我不确定如何解决问题 - 是否拆分列表,或某种交叉查询。
正如我所说,我是Python的新手,也是一般的编码。任何指针都表示赞赏 - 即使只是告诉我要研究什么。
答案 0 :(得分:4)
我使用collections.Counter
。这是一个类似于字典的结构,可以计算你给它的东西。它类似于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']
答案 1 :(得分:2)
由于你想要两个或更多朋友喜欢的任何游戏,我建议计算每个游戏的出现次数,然后返回那些出现不止一次的游戏。您可以使用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]
答案 2 :(得分:0)
您应该在合并所有子列表后使用出现次数过滤数组。我希望这个例子可以帮到你:
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'}
答案 3 :(得分:0)
您可以使用 设置 。
gameSet = set()
set([g for games in gamesList for g in games if g in gameSet or gameSet.add(g)])
list comp只会记录那些返回True
if g in gameSet
的游戏;如果他们已被添加到集合中,至少一旦他们被添加到最终列表中。
答案 4 :(得分:0)
#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]
如果信息存储在某个地方,我发现字典会很有用,因为在我看来它更容易附加,并且有更多的信息。如果您开始使用大型列表或必须经常执行此操作,迭代方法在某种程度上也会在计算上变得昂贵。但作为一个开始,我希望它有所帮助。