[英]Searching for a string in a multidimentional list and appending the sublist containing match to empty list
I have a question that is similar to this question , but mine concerns multidimentional lists like this: 我有一个类似于这个问题的问题 ,但是我的问题涉及到这样的多维数据列表:
myList = [['abc', 'abc-321'], ['def', '789-abc'], ['xyz', 'xyz-123']]
newList = []
I want to search this myList for a certain word/phrase, and if there are matches, the entire sublist to be appended to newList, with a way to control with elements are searched 我想在这个myList中搜索某个单词/短语,如果有匹配项,则会搜索要附加到newList的整个子列表,以及用元素控制的方法
For example, If I search for the the tern 'abc' in the first and second element of each sublist, newList should be (two matches): 例如,如果我在每个子列表的第一个和第二个元素中搜索tern'abc',则newList应为(两个匹配):
[['abc', 'abc-321'], ['def', '789-abc']]
but if only the first element is to be searched, newList should be (only one match): 但如果只搜索第一个元素,newList应该是(只有一个匹配):
[['abc', 'abc-402']]
How can I do both types of searches in the most efficient way? 如何以最有效的方式进行两种类型的搜索? Please consider this: The list to be searched contains around a thousand sublists and the text to be searched is about 1-2 paragraphs on average.
请考虑这一点:要搜索的列表包含大约一千个子列表,要搜索的文本平均约为1-2个段落。
Try This 尝试这个
def foo(myList,key,first=True):
if first: #First Element Search
return [x for x in myList if key in x]
else: #Search Both Element
return [x for x in myList if key in x or key in x[1]]
>>> foo(myList,'abc',0)
[['abc', 'abc-321']]
>>> foo(myList,'abc',1)
[['abc', 'abc-321'], ['def', '789-abc']]
Note: This simply utilized List Comprehension. 注意:这只是利用列表理解。 The only thing to note is the comparison.
唯一需要注意的是比较。 Comparing two string with
in
will try to match the first string any where in the second string. 将两个字符串与
in
进行比较将尝试匹配第二个字符串中任何位置的第一个字符串。 Comparing a string with a list, it will try to match the first string anywhere in the first element of the string. 将字符串与列表进行比较,它将尝试匹配字符串的第一个元素中的第一个字符串。
A simpler implementation 一个更简单的实现
def foo(myList,key,first=True):
return [x for x in myList if key in x or not first and key in x[1]]
>>> foo(myList,'abc')
[['abc', 'abc-321']]
>>> foo(myList,'abc',first=False)
[['abc', 'abc-321'], ['def', '789-abc']]
>>> foo(myList,'abc',first=True)
[['abc', 'abc-321']]
or: 要么:
def bar(L, S):
return list( v for v in L if any(S in s for s in v) )
[lst for lst in myList if any('abc' in s for s in lst)]
如果只搜索第一个元素:
[lst for lst in myList if 'abc' in lst[0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.