-1
4

2 回答 2

0

我建议将defauldict每个作者的书名分组,然后根据需要打印

from collections import defaultdict

values = [{'author__name': 'Alexandre Dumas', 'title': 'The Three Musketeer'},
          {'author__name': 'Alexandre Dumas', 'title': 'The Count of Monte Cristo'},
          {'author__name': 'Leo Tolstoy', 'title': 'Resurrection'},
          {'author__name': 'Leo Tolstoy', 'title': 'War and Peace'},
          {'author__name': 'Leo Tolstoy', 'title': 'Anna Karenina'}]

result = defaultdict(list)
for value in values:
    result[value['author__name']].append(value['title'])

for author, titles in result.items():
    print(author, ":", ",".join(f'"{title}"' for title in titles))
Alexandre Dumas : "The Three Musketeer","The Count of Monte Cristo"
Leo Tolstoy : "Resurrection","War and Peace","Anna Karenina"
于 2022-02-17T20:09:39.850 回答
0

您可以简单地使用以下代码:

import pandas as pd
data = [{'author__name': 'Alexandre Dumas', 'title': 'The Three Musketeer'},
        {'author__name': 'Alexandre Dumas', 'title': 'The Count of Monte Cristo'},
        {'author__name': 'Leo Tolstoy', 'title': 'Resurrection'},
        {'author__name': 'Leo Tolstoy', 'title': 'War and Peace'},
        {'author__name': 'Leo Tolstoy', 'title': 'Anna Karenina'}]

pd.DataFrame(data).groupby("author__name")["title"].apply(lambda x: ','.join(x)).reset_index()

输出

作者姓名 标题
0 大仲马 三个火枪手,基督山伯爵
1 列夫·托尔斯泰 复活,战争与和平,安娜卡列尼娜

解释

使用groupby,您可以对您喜欢的任何列进行分组。然后通过apply在标题列上使用,您可以根据需要加入字符串。

于 2022-02-17T20:11:44.147 回答