我有一个字符串列表:
mylist = ['foo hydro', 'bar']
以及一个名为test的字符串列表:
testI = ['foo', 'bar'] ## should succeed
testJ = ['foo'] ## should fail
testK = ['foo hydro'] ## should fail
testL = ['foo hydro', 'bar'] ## should succeed
testM = ['foo', 'bar', 'third'] ## should fail
test = [testI,testJ,testK,testL,testM]
我需要能够检查test
中每个列表的每个元素与mylist
的每个元素之间是否存在(部分或整体)字符串匹配。
因此,testI
应该成功,因为testI[0]
是mylist[0]
的部分字符串匹配,而testI[1]
是mylist[1]
的完整字符串匹配。
但是,testJ
和testK
都应该失败,因为它们只匹配mylist
中的两个字符串之一,而testM
应该失败,因为它包含一个与mylist
中的任何元素不匹配的元素
到目前为止,我已经试着和any
玩了
for i in mylist:
for j in test:
for k in j:
if any(i in b for b in k):
print("An element of mylist matches an element of test")
因此,我可以捕捉到我的列表中的任何元素是否与测试中的每个列表中的任何元素相匹配,但我无法找到满足所有需求的方法。
有什么建议吗?如果这个问题更容易处理的话,我很乐意重新考虑这个问题。
发布于 2020-05-15 10:51:08
我想为你的问题提出一个解决方案。
首先,我们创建一个函数来识别一个单词是否是另一个列表中任何单词的子字符串:
def is_substring_of_element_in_list(word, list_of_str):
if len(list_of_str) == 0:
return (False, -1)
is_sub = any([word in s for s in list_of_str])
if (is_sub == True):
ix = [word in s for s in list_of_str].index(True)
else:
ix = -1
return is_sub, ix
现在,我们可以使用这个函数来检查测试列表中的每个单词是否是列表中一个单词的子字符串。注意,我们只能使用每个单词一次,因此如果给定的单词是一个子字符串,则需要删除一个字符串。
def is_list_is_in_mylist(t, mylist):
mylist_now = sorted(mylist, key=len)
test_now = sorted(t, key=len)
counter = 0
for word in t:
is_sub, index = is_substring_of_element_in_list(word, mylist_now)
if is_sub:
mylist_now.pop(index)
test_now.remove(word)
counter += 1
if counter == len(t) and counter == len(mylist):
print("success")
else:
print("fail")
注意,我们需要对列表中的元素进行排序,以避免因单词顺序而引起的错误。例如,如果my_list = ['f', 'foo']
、test1 = ['f', 'foo']
和test2 = ['foo', 'f']
没有排序,其中一个成功,另一个将失败。
现在,您可以使用简单的for循环迭代测试:
for t in test:
is_list_is_in_mylist(t, mylist)
发布于 2020-05-15 09:22:20
我认为这段代码可能符合您的条件:
for t in test:
counter = 0
if len(t) == len(mylist):
t = list(dict.fromkeys(t))
temp = []
for s in t:
if not any([s in r for r in t if s != r]):
temp.append(s)
for l in temp:
for m in mylist:
if l in m:
counter = counter + 1
if counter == len(mylist):
print('successed')
else:
print('fail')
else:
print('fail')
https://stackoverflow.com/questions/61811098
复制相似问题