Cri*_*gus 11 python dictionary list
考虑到我有两个列表,如:
l1 = ['a', 'c', 'b', 'e', 'f', 'd']
l2 = [
'x','q','we','da','po',
'a', 'el1', 'el2', 'el3', 'el4',
'b', 'some_other_el_1', 'some_other_el_2',
'c', 'another_element_1', 'another_element_2',
'd', '', '', 'another_element_3', 'd4'
]
Run Code Online (Sandbox Code Playgroud)
我需要创建一个字典,其中键是第二个列表中的元素,在第一个列表中找到,值是在"键"之间找到的元素列表,如:
result = {
'a': ['el1', 'el2', 'el3', 'el4'],
'b': ['some_other_el_1', 'some_other_el_2'],
'c': ['another_element_1', 'another_element_2'],
'd': ['', '', 'another_element_3', 'd4']
}
Run Code Online (Sandbox Code Playgroud)
什么是更加pythonic的方式来做到这一点?
目前我这样做:
# I'm not sure that the first element in the second list
# will also be in the first so I have to create a key
k = ''
d[k] = []
for x in l2:
if x in l1:
k = x
d[k] = []
else:
d[k].append(x)
Run Code Online (Sandbox Code Playgroud)
但我很肯定这不是最好的方法,它也不是很好看:)
编辑:我还必须提到没有必要排序的列表,并且第二个列表都不必以第一个列表中的元素开头.
FHT*_*ell 10
如果这是问题的最具体陈述,我认为你会做得更好.我的意思是我会这样做,但它并没有好多少.
import collections
d = collections.defaultdict(list)
k = ''
for x in l2:
if x in l1:
k = x
else:
d[k].append(x)
Run Code Online (Sandbox Code Playgroud)
为了好玩,你也可以itertools和第三方一起做numpy:
import numpy as np
from itertools import zip_longest, islice
arr = np.where(np.in1d(l2, l1))[0]
res = {l2[i]: l2[i+1: j] for i, j in zip_longest(arr, islice(arr, 1, None))}
print(res)
{'a': ['el1', 'el2', 'el3', 'el4'],
'b': ['some_other_el_1', 'some_other_el_2'],
'c': ['another_element_1', 'another_element_2'],
'd': ['', '', 'another_element_3', 'd4']}
Run Code Online (Sandbox Code Playgroud)