首页 > 解决方案 > 通过 Python 3 查找缺失的漫画章节

问题描述

所以我有一个漫画收藏数据库数据框的例子如下:

  title chapter
0   A     1
1   A     2
2   A     3
3   A     5
4   B     2
5   B     4
6   B     7
7   C     3
8   C     1

假设每个标题可用的最新章节在上表中可用,如何用python代码识别每个标题缺少的章节?

 title chapter
0   A     4
1   B     1
2   B     3
3   B     5
4   B     6
5   C     2 

代码的输出应该可以产生如上表这样的缺失章节(不一定是表格,只要能从漫画合集数据框中找到缺失章节即可。谢谢大家输入和回答。任何帮助将不胜感激。

标签: pythonpython-3.x

解决方案


首先:欢迎使用stackoverflow!我猜你正在使用 pandas DataFrame。下次,请在您的问题中提供有关数据格式和现有代码的所有相关详细信息。

由于您的用例听起来对运行时不是很重要,因此您应该选择易于理解的简单算法。这使您对正确性充满信心。一项提议:

from pandas import DataFrame

def find_missing_chapters(comic_book_collection):
    missing_chapters = {}
    max_found = {}
    for _, row in comic_book_collection.T.iteritems():
        title = row["title"]
        chapter = row["chapter"]
        if title not in missing_chapters:
            missing_chapters.update({title: list(range(1, chapter))})
            max_found.update({title: chapter})
        else:
            if max_found[title] < chapter:
                missing_chapters[title] += list(range(max_found[title] + 1, chapter))
                max_found[title] = chapter
            else:  # if uniqueness of items in input is not guaranteed, you may want to
                   # write here: `elif chapter in missing_chapters[title]:` instead
                missing_chapters[title].remove(chapter)
    return missing_chapters


comic_book_collection = DataFrame(
    {"title": ["A"] * 4 + ["B"] * 3 + ["C"] * 2, "chapter": [1, 2, 3, 5, 2, 4, 7, 3, 1]})
print(find_missing_chapters(comic_book_collection))

输出:

{'A': [4], 'B': [1, 3, 5, 6], 'C': [2]}

推荐阅读