gpt4 book ai didi

python - 我如何将列表与 python 中的另一个列表匹配

转载 作者:行者123 更新时间:2023-12-04 07:43:37 25 4
gpt4 key购买 nike

我想在 python 中找到另一个列表值的第一个列表值,我在这里使用了 matchsetfindall还有其他方法,但在我的代码中效果不佳。
这里我想匹配那个 patternlonglist和模式总是开始。

pattern  = ['aaa','bbbb','ccc']
longlist = ['aaa845','bbbbPP44','XXX10','aaa420','ccc1','jjj7000','PPPP']

for i in longlist: # longlist is json data, So this line required. After we can do it any code
if filter(pattern.match, i):
print(i)

# other tried
if set(pattern) & set(longlist):
print(i)
愿望输出: aaa845, bbbbPP44, aaa420, ccc1任何人都可以建议没有多个的最佳编码风格 FOR循环迭代和最快的性能?

最佳答案

您可以通过 any 使用列表推导式如果找到匹配项,就会使内循环短路。
这将检查模式中的任何单词是否“包含”在 longlist 的单词中.

>>> pattern  = ['aaa','bbbb','ccc']
>>> longlist = ['aaa845','bbbbPP44','XXX10','aaa420','ccc1','jjj7000','PPPP']
>>> [i for i in longlist if any(j in i for j in pattern)]
['aaa845', 'bbbbPP44', 'aaa420', 'ccc1']
如果您想要 longlist 中的单词要“以”模式中的任何一个“开始”,那么您需要像这样更改条件。
>>> [i for i in longlist if any(i.startswith(j) for j in pattern)]
['aaa845', 'bbbbPP44', 'aaa420', 'ccc1']
在您给定的示例中,两者碰巧产生相同的结果。

关于python - 我如何将列表与 python 中的另一个列表匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67318297/

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