简体   繁体   English

如何在列表中找到与另一个列表中的字符串或子字符串匹配的字符串

[英]How do I find a string in a list that matches a string or substring in another list

How can I find a string in List1 that is a substring of any of the strings in List2? 如何在List1中找到一个字符串,该字符串是List2中任何字符串的子字符串? Both lists can be of different lengths. 两个列表的长度可以不同。

Say I have: 说我有:

List1=['hello', 'hi', 'ok', 'apple']

List2=['okay', 'never', 'goodbye']

I need it to return 'ok', seeing as it was the only string in list1 that matched list2. 我需要它返回“ ok”,因为它是list1中唯一匹配list2的字符串。

您可以将列表理解用作:

[x for x in List1 for y in List2 if x in y]

If you want to know if a string from list1 is in list2 you can do 如果您想知道list2中的字符串是否在list2中,可以执行

for s in List1:
    if s in List2:
        print("found s in List2")

I wrote this piece of code to implement the 我写了这段代码来实现

List1=['hello', 'hi', 'ok', 'apple']
List2=['ok', 'never', 'goodbye']
i=[]
for j in List1:
    for k in List2:
        if j==k:
            i.append(j)

print i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果列表中的子字符串完全包含列表中另一个字符串的子字符串,我如何在列表中找到子字符串匹配? - How do I find a substring match in a list only if it completely contains a substring of another string in a list? 如何在字符串列表中找到 substring? - How to find a substring in a string list? 如何从列中的字符串中提取与 python 列表中的另一个字符串匹配的 substring - How to extract a substring from a string in a column, that matches another string in a list in python 查找子字符串在列表中匹配的每个匹配项并创建单个字符串 - Find every occurrence where a substring matches in a list and make a single string 如何检查列表中任何 dict 的属性是否与另一个列表中的任何字符串匹配? - How do i check if a property of any dict in a list matches any string from another list? 如何在列表中查找包含给定 substring 的字符串 - How to find a string that contains a given substring in a list 检查是否存在与列表中的字符串匹配的 substring - Check if there is a substring that matches a string from a list 如何从字符串列表中删除重复的子字符串? - How do I remove repeating substring from a list of string? Python:在字符串列表中查找子字符串 - Python: Find substring in list of string 用另一个子字符串替换字符串列表中的特定子字符串 - Replace a particular substring in a list of string with another substring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM