简体   繁体   English

嵌套的Python列表理解,在第一个唯一时中断

[英]Nested Python List comprehension, break on first unique

Looking for a way to put this logic into a list comprehension: 寻找一种将这种逻辑纳入列表理解的方法:

new_bills = []
for bill in bills:
    for gnr in bill["gnrs"]:
        if timestart <= gnr["date"] <= timeend:
            new_bills.append(bill)
            break
return new_bills

So, these are two nested dictionaries, and I only want the first instance of "bill" that fits the filter. 因此,这是两个嵌套字典,我只想要适合过滤器的“清单”的第一个实例。

I used to have this: 我以前有这个:

return [bill for bill in bills for gnr in bill["gnrs"] if timestart <= gnr["date"] <= timeend]

However, this duped the bill object for everytime the if clause was met. 但是,每次满足if子句时,这都会使帐单对象受骗。 Is there a way to get a list comprehension to behave like the for loop above? 有没有一种方法可以使列表理解功能像上面的for循环一样? Keep in mind sets are out, as the bill is a dictionary (unhashable). 请紧记,因为账单是字典(不可散列)。

Edit for duplicate answer popup thing: The Solution turned out to be entirely different. 编辑重复的答案弹出框:解决方案完全不同。

Your inner loop is part of the filter: 您的内部循环是过滤器的一部分:

new_bills = [
    bill for bill in bills
    if any(timestart <= gnr["date"] <= timeend for gnr in bill["gnrs"])
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM