我这里有点奇怪。。。你知道吗
基本上说我有一个清单里面有清单。你知道吗
ratings = [
# ''' 1 star '''
["Strangers on a Train", "Anchorman", "Saw", "Suicide Squad"],
# ''' 2 star '''
["Shutter Island", "Shaun of the Dead", "Scream", "Indiana Jones"],
# ''' 3 star'''
["Goodfellas", "Mr Bean", "The Ring", "Dark Knight"],
# ''' 4 star'''
["Scarface", "Hot Fuzz", "Nosferatu", "Die Hard"],
# ''' 5 star'''
["Pulp Fiction", "Airplane", "The Omen", "Deadpool"]
]
很明显,这是一个电影列表,列表中有5个列表,给每部电影5分,尽管这个上下文非常无用。你知道吗
def rating():
if userInfo[7] == "1":
return range(5)
elif userInfo[7] == "2":
return range(2, 5)
elif userInfo[7] == "3":
return range(3, 5)
elif userInfo[7] == "4":
return range(4, 5)
else:
return range(5, 5)
这是一个函数,其中基本上返回一个范围,这取决于他们希望看到的胶片的最低评级。所以说他们的最低等级是4级,他们只会看4级和5级的电影。你知道吗
比如说他们有一个电影列表
movies = ["Strangers on a Train", "Anchorman", "Shutter Island",
"Shaun of the Dead", "Goodfellas", "Mr Bean",
"Scarface", "Hot Fuzz", "Pulp Fiction", "Airplane"]
现在我想从这个列表中删除所有不是4级或以上的电影。你知道吗
我试过了
new = []
for item in movies:
if item not in in ratings[rating()]:
new.append(item)
但这将不起作用,因为我不能使用范围来搜索大列表中的多个列表,因为它需要是一个整数。你知道吗
我知道这是一个巨大的职位,这样一个小问题,但我的大脑正在死亡,我已经尝试了几个小时,我想睡觉,但需要这样做。你知道吗
首先,对于性能搜索来说,评级数据确实不是最佳的。所以我会用字典的理解力,把电影的名字作为键,把收视率作为值来编一本字典:
(这本词典可以重复使用多次)
然后我将这些数据应用到列表理解中的第二个列表。未分级的电影得0分。你知道吗
结果:
这种方法可能不是最短的,但其优点是保留准确的评级信息,而不是“n级以上的评级”。你知道吗
你可以在其他问答中阅读list and dict comprehensions。这个问题已经很好地解释了listcomps,答案解释了dictcomps。你知道吗
相关问题 更多 >
编程相关推荐