我有一个看起来像这样的字符串列表:
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"
}
我不知道该怎么做。
只有整数才能成为关键,但其他一切必须成为价值,谢谢。
在不安装任何外部依赖项的情况下执行此操作的最简单方法是使用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'}
祝好运。
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
如果你在一行中有多个数字,它将把first number
作为key
的dict
,
>>> 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'}