【问题标题】:How to conditionally select elements in a list comprehension?如何有条件地选择列表理解中的元素?
【发布时间】:2020-01-14 22:37:04
【问题描述】:

我找不到任何符合我用例的示例。仍然在 python 列表和字典中使用我的方式。

问题:

all_cars = {'total_count': 3,'cars': [{'name': 'audi','model': 'S7'}, {'name': 'honda', 'model': 'accord'},{'name': 'jeep', 'model': 'wrangler'} ]} 

owners = {'users':[{'owner': 'Nick', 'car': 'audi'},{'owner': 'Jim', 'car': 'ford'},{'owner': 'Mike', 'car': 'mercedes'} ]} 


def duplicate(): 
   for c in all_cars['cars']: 
     if c['name'] == [c['users']for c in owners['users']]: 
        pass 
     else: 
        res = print(c['name']) 
   return res

output = ['honda', 'jeep', audi']

def duplicate(): 
   for c in all_cars['cars']: 
     if c['name'] == 'audi': 
        pass 
     else: 
        res = print(c['name']) 
   return res 

output - ['honda', 'jeep']

我正在尝试使用列表理解在两个字典中查找匹配值,然后仅返回不匹配的值。

解决方案:使用 'in' 而不是 '==' 运算符,我能够比较两个列表之间的值并跳过重复项。

def duplicate(): 
   for c in all_cars['cars']: 
     if c['name'] in [c['users']for c in owners['users']]: 
        pass 
     else: 
        res = print(c['name']) 
   return res  

【问题讨论】:

  • 你想要的输出是什么?
  • 您的“列表推导”不是有效的 Python 语法。请更新您正在使用的数据的实际格式。
  • 你能改写你的问题吗?它的措辞有点混乱。
  • @Nick 我想返回一个不重复值的列表。
  • @SunnyPatel 我刚刚更新了格式和列表理解。

标签: python python-3.x list dictionary list-comprehension


【解决方案1】:

要回答标题中的问题,您可以在列表解析期间使用语法 [x for y in z if y == a] 有条件地添加元素,其中 y == a 是您需要的任何条件 - 如果条件评估为 True,则元素 @ 987654324@ 将被添加到列表中,否则不会。

【讨论】:

    【解决方案2】:

    我只想将所有所有者数据的字典放在一起:

        ownerData = { "Shaft" : {
                  "carMake" : "Audi",
                  "carModel" : "A8",
                  "year" : "2015" },
             "JamesBond" : {
                  "carMake" : "Aston",
                  "carModel" : "DB8",
                  "year" : "2012" },
             "JeffBezos" : {
                  "carMake" : "Honda",
                  "carModel" : "Accord"
                  "year" : "1989"}
             }
    

    现在您可以像这样循环并查询它:

        for o in ownerData:
             if "Audi" in o["carMake"]:
                  print("Owner %s drives a %s %s %s" % (o, o["year"], o["carMake"], o["carModel"]))
    

    应该输出:

        "Owner Shaft drives a 2015 Audi A8"
    

    这样您就可以为所有者扩展数据集,而无需创建多个列表。

    【讨论】:

    • 所以这是从不同端点提取的两个独立数据。
    【解决方案3】:

    好的,根据您对上述解决方案的反馈,我将如何解决您的问题。将您的常见项目放入列表中,然后使用“set”打印出差异。

        all_cars = {'total_count': 3,'cars': [{'name': 'audi','model': 'S7'}, 
            {'name': 'honda', 'model': 'accord'},{'name': 'jeep', 'model': 'wrangler'} ]}
    
        owners = {'users':[{'owner': 'Nick', 'car': 'audi'},{'owner': 'Jim', 
            'car': 'ford'},{'owner': 'Mike', 'car': 'mercedes'} ]}
    
        allCarList = []
        ownerCarList = []
        for auto in all_cars['cars']:
            thisCar = auto['name']
            if thisCar not in allCarList:
                allCarList.append(thisCar)
    
        for o in owners['users']:
            thisCar = o['car']
            if thisCar not in ownerCarList:
                ownerCarList.append(thisCar)
    
        diff = list(set(allCarList) - set(ownerCarList))
        print(diff)
    

    我把它放进去运行它并得出这个输出:

        ['jeep', 'honda']
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2020-05-23
      • 2016-10-04
      • 1970-01-01
      • 2014-05-06
      相关资源
      最近更新 更多