簡體   English   中英

如何從列表中創建字典

[英]how to create a dictionary from a list

我有一個句子列表,我想將它轉換成一個詞典,只包括用戶名和年齡。

list=['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']

我想得到的輸出是一個字典

dic={David:27,John:99,rain:45}

謝謝您的幫助

您可以定義自定義函數,通過map將其應用於每個字符串,然后輸入到dict

L = ['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']

def key_value_extractor(x):
    x_split = x.split(',')  # split by ','
    name = x_split[0][1:]   # take 1st split and exclude first character
    age = int(x_split[1].rsplit(maxsplit=1)[-1])  # take 2nd, right-split, convert to int
    return name, age

res = dict(map(key_value_extractor, L))

{'David': 27, 'John': 99, 'rain': 45}

嘗試詞典理解:

dic = {x.split()[0].strip(',@'): int(x.split()[-1]) for x in member_list}

如果您需要澄清表達的各個部分,請告訴我們。

編輯:澄清,根據要求:

好的,所以:

  • 將表達式括在{}告訴它我們正在用這種理解來制作一本字典。 x表示此理解中的每個成員字符串
  • x.split()將字符串拆分為子字符串列表,在“空格”符號上(默認情況下,可以調整)

    • [0]我們抓住第一個子串[“@ David,”]
    • 使用.strip(',@')我們刪除名稱周圍的逗號和@字符
    • 有了這個,我們創建了字典鍵
  • 鍵值: int(x.split()[-1])

    • x.split()[-1]取最后一個子串('27')
    • 將它括在int()我們把它變成一個整數

您可以使用字典理解

l = ['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']


X = {item.split(',')[0][1:]:int(item.split(',')[1].rsplit(maxsplit=1)[-1]) for item in l}
print(X)

#output
{'David': 27, 'John': 99, 'rain': 45}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM