首页 > 解决方案 > 在列表不和谐python JSON文件中检测相同的项目

问题描述

在 discord PY 中,我有一个 JSON 文件,当我添加一些东西时我会写入该文件。它将它添加到列表中。

    @commands.command(pass_context=True)
    async def add(self, ctx, itemlist, *, item):
        """Usage: `!add <list> <item>`"""
        with open("list.json", "r") as f:
            data = json.load(f)
        try:
            data[itemlist].append(item)
        except KeyError:
            data[itemlist] = [item]
        with open("list.json", "w") as f:
            json.dump(data, f)
        await ctx.send("Succesfully added '{}' to the list '{}'".format(item, itemlist))

我想知道如何检测列表中是否已经存在相同的项目,然后以一种有效的方式添加重复项的数量。

例如,如果有人添加了一个苹果: !add list apple 当你查看列表时,它会说:apple

现在,当有人再次 !add list apple 时,它​​会改为显示 apple x2

标签: discord.py

解决方案


推荐阅读