我有这个用于在 Python 中过滤列表的代码:
# not working part
column_to_check_for_include = [1,2] # random result possible , could as well be [0] or [0,1,2]
column_to_check_for_exclude = [0,2,3] # random result possible , could as well be [0] or [0,1,2]
#Working part to update
content = [['John', 'is', 'cool','sometimes'],['Paul', 'is', 'bad','everytime'],['Ringo', 'may be', 'great', 'sometimes'],['Georges', 'must be', 'small', 'yesterday']]
include_criteria = ['is','must be']
exclude_criteria = ['bad','sometimes']
for row in content :
if all(exclude not in row[0] and exclude not in row[2] and exclude not in row[3] for exclude in exclude_criteria):
if any(include in row[1] or include in row[2] for include in include_criteria):
print(row)
# output ['Georges', 'must be', 'small', 'yesterday']
我想通过将所有
row[number]
替换为列表 column_to_check_for_include
和 column_to_check_for_exclude
的相应实例来执行相同的操作,因为知道这两个列表内容每次用户更新时都会更改。
类似的东西:
for row in content :
if all(exclude not in row[column_to_check_for_exclude[0]] and exclude not in row[column_to_check_for_exclude[1]] and exclude not in row[column_to_check_for_exclude[2]] for exclude in exclude_criteria):
if any(include in row[column_to_check_for_include[0]] or include in row[column_to_check_for_include[1]] for include in include_criteria):
print(row)
也许我需要重新思考整个方法,但我不知道如何处理
if
语句中条件数量会发生变化的事实(取决于列表中的项目数量)。
谢谢
解决此问题的一种方法是:
for row in content :
e=0
i=0
for exclude in exclude_criteria:
if exclude in row:
e=e+1
for include in include_criteria:
if include in row:
i=i+1
if i>0 and e==0:
print(i,e,row)