gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:00:37 25 4
gpt4 key购买 nike

我正在制作一个存在于另一个列表中的元素列表。有两个条件:

条件 1. 需要完全匹配,因此我不使用“if y in x”。

条件2、需要保留原列表的顺序

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

brands_in_df = ['Radisson Collection',
'Park Plaza', 'Radisson Red', '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', 'Park Plaza', 'Radisson Red', 'Radisson', }

最佳答案

你的“期望输出”是一个集合(花括号),但你说你想要一个列表。因此,请按如下方式使用列表理解。

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

assert result==['Radisson Collection', 'Park Plaza', 'Radisson Red', 'Radisson' ]

关于python - 使列表与另一个列表 python 完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54808346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com