社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python检查dict中的列表是否满足两个条件

bayman • 5 年前 • 1291 次点击  

给定下面的列表1,如何返回一个新列表,其中“codes”的值包含字符串“Two”,但不包含字符串“One”?

# Example, given list1:
list1 = [{'id': 11, 'codes': ['OneSeven', 'TwoThree']}, {'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}, {'id': 33, 'codes': ['SixSeven', 'OneSix']}]

# Return list with element where 'id': 22 since the string 'Two' is in codes but 'One' isn't.
list2 = [{'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55851
 
1291 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Boseong Choi
Reply   •   1 楼
Boseong Choi    5 年前
# 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']}]

如果您不喜欢多余的遍历列表,可以选择变量。

  1. 对于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)
  1. 当然,使用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)
  1. 或使用功能+理解:
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)
]

最后一个是非常可读的,但是有些人可能不喜欢声明只在一个地方使用的函数。
选择适合你情况的方法。