假设我有两个列表,例如:
NestedLst = ['1234567', 'abc456789', ['cde678945']]
SearchLst = ['123', 'cde']
如何在嵌套列表中搜索与搜索列表中任何项目的任何部分匹配,并为每个搜索项目返回子集列表。所以在这种情况下我希望输出是:
['1234567', 'abc456789', ['cde678945']] and ['cde678945']
我尝试过执行以下操作:
indices = []
for eachItem in SearchLst:
for i, elem in enumerate(NestedLst):
if eachItem in elem:
indices.append(i)
print indices
但这总是返回[0]
。任何帮助将非常感激。由于我是 Python 新手,代码的完整解释对我的学习非常有帮助。
谢谢
下面是实践中的嵌套列表示例:
[['BMNH833953:0.16529463651919140688', [[['BMNH833883:0.22945757727367316336', ['BMNH724182a:0.18028180766761139897', ['BMNH724182b:0.21469677818346077913', 'BMNH724082:0.54350916483644962085'], ':0.00654573856803835914'], ':0.04530853441176059537'], ':0.02416511342888815264', [[['BMNH794142:0.21236619242575086042', ['BMNH743008:0.13421900772403019819', 'BMNH724591:0.14957653992840658219'], ':0.02592135486124686958'], ':0.02477670174791116522', 'BMNH703458a:0.22983459269245612444'], ':0.00000328449424529074', 'BMNH703458b:0.29776257618061197086'], ':0.09881729077887969892'], ':0.02257522897558370684', 'BMNH833928:0.21599133163597591945'], ':0.02365043128986757739', 'BMNH724053:0.16069861523756587274'], ':0.0;\n']
最佳答案
您可以使用方法和递归来做到这一点:
NestedLst = ['1234567', 'abc456789', ['cde678945']]
SearchLst = ['123', 'cde']
def get_list(a,b):
for i in b:
if type(i)==list: #if this is a nested list, do the same function for the contents of that list, returning that list if it meets the conditions.
return get_list(a,i)
elif a in i: #if element in list is not a nested list, just do normal check for containment using in
return b
return []
x = [get_list(i,NestedLst) for i in SearchLst] #just calls the function for all search terms
for k in x:
print k
[OUTPUT]
['1234567', 'abc456789', ['cde678945']]
['cde678945']
关于python - 根据替代列表中的项目搜索嵌套列表,返回包含部分匹配的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23183781/