加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使列表与另一个列表python完全匹配

发布时间:2020-12-17 17:37:59 所属栏目:Python 来源:网络整理
导读:我正在列出另一个列表中存在的元素列表.有两个条件: 条件1.需要完全匹配,因此我不使用“如果x中的y”. 条件2.必须保留原始列表的顺序. rhg_brands = ['Radisson Collection','Radisson Blu','Park Plaza','Radisson Red','Radisson']brands_in_df = ['Radis

我正在列出另一个列表中存在的元素列表.有两个条件:

条件1.需要完全匹配,因此我不使用“如果x中的y”.

条件2.必须保留原始列表的顺序.

rhg_brands = ['Radisson Collection','Radisson Blu','Park Plaza','Radisson Red','Radisson']

brands_in_df = ['Radisson Collection','Radisson']

#remove brands from rhg_brands if they're not in the brands_in_df 
rhg_brands = set(rhg_brands).intersection(set(brands_in_df))  

#output:
{'Park Plaza','Radisson','Radisson Collection','Radisson Red'}

我希望输出以某种方式保留原始列表的顺序.

下面是所需输出的示例:

{'Radisson Collection',}
最佳答案
您的“所需输出”是一组(花括号),但是您说您想要一个列表.因此,请按以下方式使用列表理解.

result = [x for x in rhg_brands if x in brands_in_df]

assert result==['Radisson Collection','Radisson' ]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读