[英]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.