python如何根据一个list里的元素对另一个list里的元素进行分类呢?

例如现在有a = ['df', 'et', 'rt'] b =['wodf', 'asdf', 'qwet', 'wert']两个list,根据a中的元素对b进行分类,最终想要得到{'df' : ['wodf', 'asdf'], 'et' : ['qwet'], 'rt' : [wert]}。

d={}
for i in a:
    d[i]=[k for k in b if i in k]

[willie@localhost ~]$ python3

Python 3.5.2 (default, Dec  7 2016, 23:38:49) 

[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> a = ['df', 'et', 'rt']

>>> b =['wodf', 'asdf', 'qwet', 'wert']

>>> d={}        

>>> for i in a:

... d[i]=[k for k in b if i in k]

... 

>>> d

{'rt': ['wert'], 'df': ['wodf', 'asdf'], 'et': ['qwet']}

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答