簡體   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