2011-10-08 45 views
2

你將如何把這個字符串列表:那給你這個的Python:創建包含類型的字典

str='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5' 

到一個列表:

print x[1]['building']=CL5 

具體做法是:

x=[{'ldap':'alberthwang','eeid':'67739'},{'ldap':'meng','eeid':'107','building':'CL5'}] 

我試圖首先拆分字符串並追加到列表中:

sample=[] 
for s in str.split('|'): 
    sample.append(s) 

但我堅持如何將列表項目變成字典,然後我可以用來填充另一個列表。

回答

4
text='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5' 
sample=[ 
    dict(item.split(':') for item in part.split(',')) 
    for part in text.split('|')] 
print(sample) 
# [{'eeid': '67739', 'ldap': 'alberthwang'}, {'building': 'CL5', 'eeid': '107', 'ldap': 'meng'}] 

print(sample[1]['building']) 
# CL5 
  1. List comprehensions是構建 列表,如這是一個非常方便的方式。
  2. A dict can be constructed來自可迭代的鍵值對。上面使用的迭代器是一個generator expression
  3. str是一個內置類型,所以指定一個字符串str覆蓋 內置。最好選擇其他變量名稱以避免將來出現令人驚訝的錯誤。

我讀,寫向後列表理解:

[ expression   # (3) 
    for variable in  # (2) 
    iterable    # (1) 
] 

(1):首先,瞭解迭代。在上面的解決方案中,這是text.split('|')

(2):for variable in原因variable被分配到iterable中的值,一次一個。

(3):最後,expression可以是任何Python表達式,(通常)使用variable

生成器表達式的語法幾乎相同。列表理解與生成器表達式之間的區別在於列表理解返回一個列表,而生成器表達式返回一個迭代器 - 一個按需產生其內容的對象(當它被循環時,或者調用next時)而不是像list s那樣一次生成所有項目。

如果列表很長,則列表可能消耗大量內存。 生成器表達式會消耗更少的內存(甚至可能無限),因爲並非所有元素都必須同時存在於內存中。

+0

我肯定會花大量的時間環繞我的頭周圍列表解析 – jwesonga

0

使用str作爲變量名是個壞主意,因爲它掩蓋了內置的str

s ='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5' 
res = [dict(colonStr.split(':') for colonStr in ds.split(',')) 
     for ds in s.split('|')] 

將結果存儲在res中。

0

這裏的關鍵洞察是dict可以採取鍵/值對列表。所以,你可以使用這樣的理解這樣做:

string = 'ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5' 

list_of_dicts = [dict(item.split(':') for item in items.split(',')) for items in string.split('|')] 
print list_of_dicts 
0

也許是這樣的:

>>> s = 'ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5' 
>>> x = [dict([d.split(':') for d in ls.split(',')]) for ls in s.split('|')] 
>>> x[1]['building'] 
>>> 'CL5'