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

问题描述 投票:0回答:3

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

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"
}

我不知道该怎么做。

只有整数才能成为关键,但其他一切必须成为价值,谢谢。

python list dictionary
3个回答
0
投票

在不安装任何外部依赖项的情况下执行此操作的最简单方法是使用findall模块中的re方法。

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'}

祝好运。


1
投票
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

1
投票

如果你在一行中有多个数字,它将把first number作为keydict

>>> 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'}
© www.soinside.com 2019 - 2024. All rights reserved.