我有一個資料串列,想從另一個串列中獲取匹配關鍵字后的值并將其附加到字典中。它應該一直運行,直到下一個關鍵字匹配并添加到新字典中。
a = ['Experience',
'Software Engineer',
'EY',
'Sep 2018 - Present',
'Education',
'xyz College',
'Bachelor of Technology - BTech, Computer Science',
'2014 - 2017',
'Licenses',
'The Joy of Computing using Python ',
'NPTEL',
'Issued Jan 2020']
b = ['Experience', 'Education', 'Licenses']
預期結果:
c =
{'Experience':['Software Engineer','EY', 'Sep 2018 - Present']},
{'Education':['xyz College','Bachelor of Technology - BTech, Computer Science','2014 - 2017']},
{'Licenses':
['The Joy of Computing using Python ','NPTEL','Issued Jan 2020']}
for i in a:
j = a.index(i)
k = 1
while i in b:
c[i].append(a[j 1])
if i == a[k]:
k =1
break
else:
j =1
但邏輯不正確,我被困在這里。
uj5u.com熱心網友回復:
我會做一個 dict-comprehension 并分別附加最后一個元素:
c = {keyword:a[a.index(keyword) 1:a.index(next_keyword )] for keyword, next_keyword in zip(b, b[1:])}
c[b[-1]] = a[a.index(b[-1]):]
print(c)
# {'Experience': ['Software Engineer', 'EY', 'Sep 2018 - Present']}
# {'Education': ['xyz College', 'Bachelor of Technology - BTech, Computer Science', '2014 - 2017']}
# {'Licenses': ['Licenses', 'The Joy of Computing using Python ', 'NPTEL', 'Issued Jan 2020']}
uj5u.com熱心網友回復:
您可以遍歷a,curr_key如果在串列中找到變數,則將其更改為鍵b并將元素附加到該鍵。
c = {}
curr_key = None
for string in a:
if string in b:
curr_key = string
else:
c.setdefault(curr_key, []).append(string)
print(c)
輸出:
{'Experience': ['Software Engineer', 'EY', 'Sep 2018 - Present'],
'Education': ['xyz College',
'Bachelor of Technology - BTech, Computer Science',
'2014 - 2017'],
'Licenses': ['The Joy of Computing using Python ',
'NPTEL',
'Issued Jan 2020']}
uj5u.com熱心網友回復:
我修改了變數名以便更好地理解:
for keyword in b:
c[keyword] = []
for i in range(len(a)):
if a[i] == keyword:
c[keyword].append(a[i 1])
c[keyword].append(a[i 2])
c[keyword].append(a[i 3])
uj5u.com熱心網友回復:
使用回圈的一種方法(假設您有唯一的鍵):
B = set(b)
c = {}
key = None
for s in a:
if s in B:
key = s
c[key] = []
elif key is not None:
c[key].append(s)
print(c)
輸出:
{'Experience': ['Software Engineer', 'EY', 'Sep 2018 - Present'],
'Education': ['xyz College',
'Bachelor of Technology - BTech, Computer Science',
'2014 - 2017'],
'Licenses': ['The Joy of Computing using Python ',
'NPTEL',
'Issued Jan 2020']}
如果你真的想要一個單獨的字典串列:
B = set(b)
c = []
key = None
for s in a:
if s in B:
key = s
d = {key: []}
c.append(d)
elif key is not None:
d[key].append(s)
print(c)
輸出:
[{'Experience': ['Software Engineer', 'EY', 'Sep 2018 - Present']},
{'Education': ['xyz College', 'Bachelor of Technology - BTech, Computer Science', '2014 - 2017']},
{'Licenses': ['The Joy of Computing using Python ', 'NPTEL', 'Issued Jan 2020']}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530223.html
上一篇:隨機過濾python字典串列以獲取基于相同鍵名的新字典串列
下一篇:從關鍵字中獲取列 計數出現
