【问题标题】:Updating A Json in a more efficient way以更有效的方式更新 Json
【发布时间】:2022-01-25 14:57:03
【问题描述】:
[
{"923390702359048212": 5},
{"462291477964259329": 1},
{"803390252265242634": 3},
{"824114065445486592": 2},
{"832041337968263178": 4}
]

这是我刚刚随机制作的用户 ID 列表以及每个 ID 具有的一些样本编号。在这种情况下,我们将其称为电子游戏中一个赛季的进球数。当我尝试更新游戏结束时的进球数时,我必须绕道而行,首先获取服务器中的所有成员 id,然后使用以下代码将其与数据进行比较。

amount = 0
for member in server:
    if member.id != server.member.id:
        amount = amount + 1
    else:
        print(amount)
        print(str(member.id), str(server.member.id))
        print(jsondata[amount][str(server.member.id)])
        break
    
jsondata[amount][str(server.member.id) = jsondata[amount][str(server.member.id)] + 1

有没有更好的方法来做我正在做的事情?我知道我最终会遇到问题,因为我不会在 json 上列出成员,直到他们进球,而且我觉得我通过检查很多成员来浪费我的程序的大量时间(我编辑了我的真实列表并制作了这个列表以使其更容易,因为没有人需要查看 50 多个条目来获得这个想法)。在这方面我仍然是初学者,所以请用简单的术语回答或留下链接到我可以学习更复杂想法的地方。谢谢

    def goalscored():
        amount = 0
        for member in server:
            if member.id != server.member.id:
                amount = amount + 1
            else:
                print(amount)
                break
        with open('Goals.json','w') as f:
            jsondata = json.load(f)
            jsondata[amount][str(server.member.id) = jsondata[amount][str(server.member.id)] + 1
            json.dump(jsondata,f)
    
    def firstgoal(server.member.id):
        with open('Goals.json','w') as f:
            jsondata = json.load(f)
            amount = 0
            goalscored = 1
            totalmembers = server.members.amount
            for member in server:
                if membed.id !=server.member.id:
                    amount = amount + 1
                if amount == totalmembers:
                    NewScore = {user.id:goalscored}
                    json.dump(NewScore,f)

我正在使用的代码

【问题讨论】:

  • 您上面的列表中哪个是member.id,哪个是server.member.id
  • server.member.idmember.id 相同。 server.member.id 正在 json 中使用,但它们是相同的 id。我将它相互比较的原因是我可以在列表中找到正确的数字,以便我知道在哪里调用 json 以获取 jsondata[amount][server.member.id] 中的正确数据
  • 与其遍历列表来查找字典的索引,为什么不制作一个字典并直接通过成员 ID 引用目标?
  • 请分享一个完整的可重现示例。
  • 你能用一种简单的方法来回应吗?我最初有类似的东西,但我收到错误,说没有找到 json 的结尾,我对此无能为力。 @Manlai

标签: python json


【解决方案1】:

不知道为什么你不能早点让它工作,但将它存储为 dict 会容易得多。

# file.json
{
 "923390702359048212": 5,
 "462291477964259329": 1,
 "803390252265242634": 3,
 "824114065445486592": 2,
 "832041337968263178": 4
}

def goalscored():
    with open("Goals.json", "r") as f:
        jsondata = json.load(f)
        # Make sure your id is not int but str
        if server.member.id not in jsondata:  # first goal case
            jsondata[server.member.id] = 0
        jsondata[server.member.id] += 1

    with open("Goals.json", "w") as f:
        json.dump(jsondata, f)

【讨论】:

  • 谢谢你。我才意识到我非常愚蠢。我尝试将每个用户标识设置为他们自己的字典,这导致文件没有结尾的错误。非常感谢
猜你喜欢
  • 1970-01-01
  • 2012-07-18
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多