繁体   English   中英

如何将字符串列表转换为dict,其中只有未知索引处的某种类型才能成为键?

[英]How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys?

我有一个看起来像这样的字符串列表:

myList = [
  "this 1 is my string",
  "a nice 2 string",
  "string is 3 so nice"
]

我想将此字符串转换为看起来也像这样的dict

{
  "1": "this is my string",
  "2": "a nice string",
  "3": "string is so nice"
}

我不知道该怎么做。

谢谢,只有整数可以成为键,而其他所有东西都必须成为值。

如果一行中有多个数字,它将以第first numberdictkey

>>> for line in myList:
...   match = re.search(r'\d+',line)
...   if match:
...     num = match.group()
...     newline = line.partition(num) # control over the partition
...     newline = newline[0].strip() + ' '.join(newline[2:])
...     d[num] = newline
... 
>>> 
>>> d
{'1': 'this is my string', '3': 'string is so nice', '2': 'a nice string'}
import re

myDict = {}

for element in myList:
    # Find number using regex.
    key = re.findall(r'\d+', element)[0]
    # Get index of number.
    index = element.index(key)
    # Create new string with index and trailing space removed.
    new_element = element[:index] + element[index + 2:]
    # Add to dict.
    myDict[key] = new_element

不安装任何外部依赖项的最简单方法是使用re模块中的findall方法。

from re import findall

def list_to_dict(lst):
  result = {}
  for value in lst:
    match = findall(r"\d", value)
    if len(match) > 0:
      result[match[0]] = value.replace(match[0], "").replace("  ", " ")
  return result

如果愿意,可以将0索引替换为另一个索引,尽管只有在确定知道整数索引在哪里的情况下才应该这样做。

然后使用您的列表:

my_list = [
  "this 1 is my string",
  "a nice 2 string",
  "string is 3 so nice"
]

您可以像下面这样调用该函数:

print(list_to_dict(my_list))

哪个应该输出这个dict

{'1': 'this is my string', '2': 'a nice string', '3': 'string is so nice'}

祝好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM