python - 如何在 for 循环中部分匹配 Python 中的列表?

标签 python list

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)

我有这个 for 循环,它从列表列表中选择列表。它应该部分匹配 criteria_list 的开头元素,并排除后面的某些关键字元素,例如镜像元素。

问题在于它与criteria_list的开始序列不部分匹配。所以本质上它返回 ['section', 'section', 'section', 3, 'light',]['subsection', 'section', 'section', 3, 'light',] 而不仅仅是

['section', 'section', 'section', 3, 'light',] 因为 'subsection' 元素与 criteria_list 的序列不匹配?

最佳答案

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

如果 criteria_list 上元素的顺序很重要,则此方法有效。

我使用列表切片来仅获取 Final_list 子列表的前 4 个元素,并与整个条件列表进行比较。

关于python - 如何在 for 循环中部分匹配 Python 中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44589369/

相关文章:

python - 使用键字符串列表作为路径添加到字典

c# - 通过 lambda 从另一个集合中排除一个集合

javascript - 过滤掉嵌套列表中具有特定键的字典元素

python - Python 中的单词数统计

python - 请求方法值错误的 Django Rest Framework : `get_serializer_class` called several times,

python - 合并具有不一致键的多个字典

python - 计算两个列表中的对,当相乘时形成一个完美的平方

c++ - 如何从链表中删除节点?

python - 维度为 1 的 numpy 数组与没有该维度的 numpy 数组有什么区别

python - 单元测试中的模拟日志处理程序