如何在for循环中部分匹配Python中的列表?
我有一个for循环,它从列表列表中选择列表。它应该部分匹配criteria_list的开始元素,并且还排除后面的某些关键字元素,例如mirror元素 问题在于它没有部分匹配如何在for循环中部分匹配Python中的列表?,python,list,Python,List,我有一个for循环,它从列表列表中选择列表。它应该部分匹配criteria_list的开始元素,并且还排除后面的某些关键字元素,例如mirror元素 问题在于它没有部分匹配标准列表的开始序列。所以本质上它返回的是['section','section','section',3','light',] 和['subsection','section',section',3','light',]而不仅仅是 ['section','section','section',3','light',]因为'su
标准列表的开始序列。所以本质上它返回的是['section','section','section',3','light',]
和['subsection','section',section',3','light',]
而不仅仅是
['section','section','section',3','light',]
因为'subsection'元素与标准列表的顺序不匹配
final_list = [
['section', 'section', 'section', 3, 'mirror', 0, 'blue'],
['section', 'section', 'section', 3, 'mirror'],
['section', 'section', 'section', 3, 'light',],
['subsection', 'section', 'section', 3, 'light',]
]
criteria_list = ['section', 'section', 'section', 3]
cp = True
exclude_keyword = 'mirror'
for each_list in final_list:
for check in criteria_list:
if check in each_list and exclude_keyword not in each_list:
cp = True
else:
cp = False
if cp == True:
print(each_list)
如果条件_列表中元素的顺序确实重要,则此操作有效
我使用list切片
仅获取最终列表子列表的前4个元素,并与整个标准列表进行比较。您得到的输出与您得到的一样,因为您从未检查内部列表和标准列表的开头是否相等,您只需检查每个内部元素中是否存在标准列表中的元素
有效的代码:
final_list = [
['section', 'section', 'section', 3, 'mirror', 0, 'blue'],
['section', 'section', 'section', 3, 'mirror'],
['section', 'section', 'section', 3, 'light',],
['subsection', 'section', 'section', 3, 'light',]
]
criteria_list = ['section', 'section', 'section', 3]
exclude_keyword = 'mirror'
for lista in final_list: # Loop through the main list
if lista[:len(criteria_list)] == criteria_list and exclude_keyword not in lista: # checks if first elements are equal your criteria_list (if the order doesn't matter, this won't work). And checks if excluded_keyword is not inside this sublist.
cp = True
print(lista) # prints sublist.
else:
cp = False
最终列表
和标准列表
中元素的顺序是否重要?顺便说一句,在您的代码中检查标准列表
中的每个元素,以及它是否包含在最终列表
的内部列表中。因此,如果内部列表类似于['abc','def','section',3]
,那么它也将返回True
,您可能不想知道顺序的重要性,我更希望如果它返回True只是开始序列匹配,那么内部列表必须以'section'
开头,对吗?你的意思是当订单不重要时,请注意这不是一个通用的解决方案,因为匹配的长度是硬编码的……是的,订单很重要,条件列表的顺序是我想要匹配的,然后是之后的任何内容,只要不使用exclude\u关键字,这都不重要included@brunodesthuilliers已经更改了,所以不再硬编码,谢谢你的建议。@Darth如果订单重要,试试我的代码,它对我有用。你可能想做一些事情,检查每个\u列表是否为非-empty@kuro你完全正确(我会得到索引器
)!我修正了密码。非常感谢。
final_list = [
['section', 'section', 'section', 3, 'mirror', 0, 'blue'],
['section', 'section', 'section', 3, 'mirror'],
['section', 'section', 'section', 3, 'light',],
['subsection', 'section', 'section', 3, 'light',]
]
criteria_list = ['section', 'section', 'section', 3]
cp = True
exclude_keyword = 'mirror'
for each_list in final_list:
cp = False
if exclude_keyword not in each_list and each_list:
# you don't need to check for equality of the beginning
# if you got your exclude keyword
for index, check in enumerate(criteria_list):
if check == each_list[index]:
cp = True
else:
# if at some index equality fails then you should stop comparing
cp = False
break
if cp == True:
print(each_list)