在Python中,如何在保持单词顺序的同时从两个列表中查找常用单词? [英] In Python, how do I find common words from two lists while preserving word order?

查看:42
本文介绍了在Python中,如何在保持单词顺序的同时从两个列表中查找常用单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种简单的方法来做到这一点:

I am trying to find an easy way to do this:

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']

我想获得两个列表的共同元素,而list1的顺序保持不变,因此可以预期此结果.

I want to get common elements of the two lists, with list1's order untouched, so this result is expected.

list3 = ['little','blue']

我正在使用

list3 = list(set(list1)&set(list2))

但是,这只会返回list3 = ['blue','little'],显然,set()只是忽略了顺序.

however, this only returns list3 = ['blue', 'little'], obviously, set() just ignore the order.

任何帮助将不胜感激!

推荐答案

您快到了,只需根据list1

list1 = ['little','blue','widget']
list2 = ['there','is','a','little','blue','cup','on','the','table']

list3 = set(list1)&set(list2) # we don't need to list3 to actually be a list

list4 = sorted(list3, key = lambda k : list1.index(k))

结果:

>>> list4
['little', 'blue']

这篇关于在Python中,如何在保持单词顺序的同时从两个列表中查找常用单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆