【问题标题】:Concatenate index of a list into a string variables将列表的索引连接到字符串变量中
【发布时间】:2022-01-18 09:00:30
【问题描述】:

我有一个清单

list = ['1a-b2', '2j-u3', '5k-hy', '1h-j3']

我有一个像下面这样的字符串

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2y-9k"}'

如何将字符串中的id 值替换为其在主列表中的相应索引?

例如, 我想用list 中的索引替换main 字符串中的“1h-j3”。这也需要在一个循环中完成。

我尝试使用 +、% 进行连接,但它们不起作用,请帮助我。列表索引和主变量都是字符串数据类型

预期输出如下 在第一个循环中

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}'

在第二个循环中

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}'

在第三个循环中

main = '{"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}'

等等

【问题讨论】:

  • 我尝试阅读您的问题 3 次,但我仍然不明白您要做什么。 1hj3 是什么意思? 在循环中添加每个索引是什么意思?另外,到目前为止你写了什么代码?哪里出了问题?
  • main 会是有效的 JSON 吗?
  • 这是一个类别 id,main 是 url 的一种参数,我只想用我的类别 id 代替这个“1h-j3”
  • 我只想知道我是否可以在这个字符串中使用我的索引,如果可以,那么如何,因为我尝试了几种连接技术,但它们不起作用
  • @MalikZaib 1h-j3 不是您提供的列表的一部分。如果您说id 的值保证在列表中,并且您只想使用列表中id 值的索引,那么请重新提出您的问题。我认为@Kris 在下面为您提供了答案。

标签: python list concatenation


【解决方案1】:

好吧,我可以根据您对 main 变量拥有的数据类型想到 2 种方法。见下文。

如果该值是正确的 JSON

import json

items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
# if main_dict was a valid json
main_dict = json.loads('{"datatype": "null", "country_code":"eu","offset":0,"id":"1h-j3"}')
main_dict["id"] = items_list.index(main_dict["id"])
main_dict = json.dumps(main_dict)

其他情况,它是一个肮脏的字符串操作。可能有更好的方法,

# If its not a valid JSON
str_main = '{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}'
import re

# Use a regex to find the key for replacement.
found = re.findall(r'"id":".*"', str_main, re.IGNORECASE)
if found and len(found) > 0:
    key = found[0].split(":")[1].replace('"', '')
    _id = items_list.index(key)
    str_main = str_main.replace(key, str(_id))

print(str_main)

产生的输出

{"datatype: null" "country_code":"eu","offset":0,"id":"3"}

--更新--

根据您更新的要求,我假设这将是一个简单的循环,如下所示。

items_list = ['1a-b2', '2j-u3', '5k-hy', "1h-j3"]
base_str = '{"datatype: null" "country_code":"eu","offset":0,"id":"_ID_"}'
for item in items_list:
     main = base_str.replace('_ID_', item)
     print(main)

产生类似的输出

{"datatype: null" "country_code":"eu","offset":0,"id":"1a-b2"}
{"datatype: null" "country_code":"eu","offset":0,"id":"2j-u3"}
{"datatype: null" "country_code":"eu","offset":0,"id":"5k-hy"}
{"datatype: null" "country_code":"eu","offset":0,"id":"1h-j3"}

【讨论】:

  • 感谢@kris,但我可以在输出中获取索引值而不是“3”
  • 好吧,您可以在问题本身中发布输入、预期输出等。这是我能理解的。此代码在该上下文中运行良好:-)
  • 我已经用预期的输出更新了问题,你可以再看一次吗,谢谢
  • 我已经更新了答案,我想这就是你所需要的。 !
  • 谢谢@kris,它就像一个魅力,卡在上面几天,再次感谢您的帮助,真的很感谢它
猜你喜欢
  • 1970-01-01
  • 2018-08-23
  • 2021-06-23
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多