gpt4 book ai didi

python - 在两个列表中查找匹配的子串

转载 作者:太空宇宙 更新时间:2023-11-03 13:59:28 24 4
gpt4 key购买 nike

我有两个列表:A 和 B。列表长度不相同,并且它们都包含字符串。匹配两个列表中的子字符串的最佳方法是什么?

list_A = ['hello','there','you','are']
list_B = ['say_hellaa','therefore','foursquare']

我想要一个名为 list_C 的匹配子字符串列表,其中包含:

list_C = ['hell','there','are']

我遇到了 this答案,但它要求我有一个匹配子串的列表。有没有一种方法可以在不手动创建匹配子字符串列表的情况下获得我想要的内容?

This也无济于事,因为第二个列表包含子字符串。

最佳答案

这是一种方法。使用列表理解

list_A = ['hello','there','you','are']
list_B = ['hell','is','here']
jVal = "|".join(list_A) # hello|there|you|are

print([i for i in list_B if i in jVal ])

输出:

['hell', 'here']

关于python - 在两个列表中查找匹配的子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51085180/

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