【问题标题】:How to change the value of a JSON list?如何更改 JSON 列表的值?
【发布时间】:2022-01-10 00:59:36
【问题描述】:

我知道这个问题之前已经被问过。我看了以下帖子:

Python replace values in unknown structure JSON file

How to find and replace a part of a value in json file

https://pretagteam.com/question/how-to-replace-a-value-in-json-file-using-python

How to find and replace a part of a value in json file(不知何故这就是我正在寻找的,但它不适合我的问题,因为链接不同并且全部存储在“最新”下)

还有更多的贡献,但是我仍然卡住了。

我有一个像这样的简单 JSON 结构:

{
  "guild1": {
    "latest": [
      "link1",
      "link2"
    ],
    "channel": channel_here
  },
  "guild2": {
    "latest": [
      "link"
    ],
    "channel": channel_here
  }
}

我找到了一种方法来遍历条目并打印找到条件的列表,例如:

# searching for link 1
["link1", "link2", "link3"] # here link 1 for example is found in one of the list entries
["link5"] -> This for example does not match what I am looking for, I can ignore this

如果找到,我只想用另一个之前定义的值替换它(只是link1)。我试图遍历找到列表的keys,但无法.replace 它或其他东西。与我的搜索条件匹配的键被打印出来,但我不能用它做任何其他事情。是否可以如此简单地更改列表中的条目?

主要是我也得到了以下错误,我也查过但没有得到任何更明智的错误:

TypeError: string indices must be integers

这是我搜索列表结尾“条目”的方式:

if defined_link in data[searchloop]['latest']: # data is my JSON file, searchloop the for-loop
    for key in data[searchloop]['latest']: # Get all the matching keys
        if key == defined_link: # Get the key I am looking for

也许其他人可以在这里帮助我!

【问题讨论】:

  • 您说您尝试并做了几件事,但您没有提供任何 Python 代码,除了用于字符串列表的两个文字 - 您能否提供代码示例,解释发生了什么以及你期望的结果是什么?
  • @Grismar 抱歉,正在编辑帖子。再看看!
  • 我是否理解正确,您希望找到任何出现的 ["link1", "link2", "link3"] 并用其他东西替换它们?你想用什么来代替它们?你想让他们在一个和所有的“公会”中被替换吗?
  • @Grismar 我已经能够使用这个提供的循环找到属于我的搜索条件的所有链接。我想用一个新链接替换这些找到的链接,为此我只是将"https://www.google.de/" 作为测试,但当然没有发生任何事情。如果在每个“公会”中找到,我想替换它。

标签: python json discord.py


【解决方案1】:

此代码会将列表中的一个值(此处为“link1”)更改为另一个值:

L = ["link1", "link2", "link3"]
L[L.index('link1')] = 'someOtherValue'

在这之后你会看到 L 变成了 ["someOtherValue", "link2", "link3"]

你首先找到'link1'在哪个索引,假设你返回3。所以,你知道你必须改变L[3]的值。现在很简单。做 L[3] = 'someOtherValue'。

【讨论】:

  • 这非常有效。谢谢!您是否知道索引是否可能会提高性能?
  • .index() 函数不是索引而是在列表中搜索一个值,在上面的例子中恰好是“link1”。时间复杂度是 O(n)(很可能,只有 99% 的把握)。所以,是的,搜索列表会影响性能。但取决于列表有多大 (O(n)) 以及服务器上的用户会调用多少次此函数。
  • 此代码每 30 秒运行一次,需要对其进行更多测试以确保它可以运行。但它不会有超过 10000 个“链接”
【解决方案2】:

遍历 json 结构中的每个公会。

遍历该公会“最新”列表中的每个链接。

如果链接匹配,则将该列表项分配给其他项。

for guild in jsonstructure:
    for i in range(len(jsonstructure[guild]['latest'])):
        if jsonstructure[guild]['latest'][i] == 'something':
            jsonstructure[guild]['latest'][i] = 'new thing'

【讨论】:

  • 嗨,约翰,感谢您的回答。这似乎也是一个可行的答案。你认为如果我有很大的列表,我会因为一遍又一遍地循环 JSON 而失去性能吗?否则我更喜欢这种方法,因为Kushal Kumar 的答案可能需要很多性能。
【解决方案3】:

我觉得你应该试试 list.append(i) 它会工作我遇到同样的问题

例如:

string = "Hello World!"

list = []

for i in string:

     list.append(string[i])

print(list)

【讨论】:

  • appending 在这种情况下为我增加了一个新的价值,如果我直接理解你的代码的话。不过,我想替换列表中的某些内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多