# Example, given list1:
list1 = [{'id': 11, 'codes': ['OneSeven', 'TwoThree']}, {'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}, {'id': 33, 'codes': ['SixSeven', 'OneSix']}]
list2 = [
d for d in list1
if any(
'Two' in word
for word in d['codes']
) and all(
'One' not in word
for word in d['codes']
)
]
print(list2)
输出:
[{'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}]
如果您不喜欢多余的遍历列表,可以选择变量。
-
对于Python3.8或更高版本,可以执行以下操作:
# Example, given list1:
list1 = [{'id': 11, 'codes': ['OneSeven', 'TwoThree']}, {'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}, {'id': 33, 'codes': ['SixSeven', 'OneSix']}]
list2 = [
d for d in list1
if 'Two' in (text := ' '.join(d['codes'])) and 'One' not in text
]
print(list2)
-
当然,使用for语句而不是comprehension,您可以使用3.7或更早的版本来实现这一点。
list2 = []
for d in list1:
text = ' '.join(d['codes'])
if 'Two' in text and 'One' not in text:
list2.append(d)
-
或使用功能+理解:
def check_condition(data: dict) -> bool:
text = ' '.join(data['codes'])
return'Two' in text and 'One' not in text
list2 = [
d for d in list1 if check_condition(d)
]
最后一个是非常可读的,但是有些人可能不喜欢声明只在一个地方使用的函数。
选择适合你情况的方法。