【问题标题】:Compare two lists and create multiple lists based on matching data比较两个列表并根据匹配数据创建多个列表
【发布时间】:2017-09-14 13:45:35
【问题描述】:

我有一个包含 20 部电影的列表,保存如下:

library = [
['name1','director1','genre1',running_time_in_mins_1],
['name2','director2','genre2',running_time_in_mins_2],

等到20个

基于该库,我需要能够显示特定类型的所有电影的平均运行时间。我希望输出如下内容:“xyz 的平均运行时间是 ### 分钟”。库中可能有任意数量的类型(我的库中目前有 6 个)或电影。

我可以使用

创建一个独特的流派列表
genre=[]
for y in range (0,len(library)):
    if (library[y][2]) not in genre:
        genre.append(library[y][2])

然后我想我会为每种类型创建单独的列表并添加匹配的运行时间,但这不起作用

for x in range (len(library)):
    for z in range(0,(len(genre))):
        if library[x][2] == genre[z]:
            z=[]
            z.append(library[x][3])
print(z)

【问题讨论】:

  • 将你的列表导入pandas并使用groupby。

标签: python-3.x list loops match


【解决方案1】:

pandas 是一个很好的库,可以做你想做的事,虽然学习起来有点棘手。

现在,试试:

for genre in set(row[2] for row in library):
    times = [row[3] for row in library if row[2]==genre]
    print("average runtime for", genre, "is", sum(times)/len(times))

【讨论】:

    【解决方案2】:

    List comprehensions 是一个非常有用的工具

    获取唯一导演列表:

    >>> library = [['n1', 'd1', 30], ['n2', 'd2', 40], ['n1', 'd2', 20]]
    >>> set([x[1] for x in library])
    set(['d2', 'd1'])
    

    获取特定名称的时间列表

    >>> times = [x[2] for x in library if x[0] == 'n1']
    [30, 20]
    

    计算平均时间

    >>> sum(times) / len(times)  # python 3
    25
    

    但是列表列表确实不是最优的,并且使代码不可读(x[0] 是什么?)。根据你获取数据的方式、你想用它做什么以及你想花多少时间学习更多的 python/库,我建议:字典列表、类列表、pandas 数据框或数据库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多