简体   繁体   中英

How do I stop list comprehension once i get an item above certain condition limit

I need a small clarification of how to approach it. I have a list 'm', and i'm iterating through to find an integer above a certain limit, say '90'. I want to stop iterating once this limit is achieved and post the item (that is meeting the condition). For example, if 98.877 is the item, i have to append it to a new list(see below snippet).

Problem

My challenge is that I get to extend only the item the comes before the item that meets the condition. I'd appreciate your help.

m = [('a', 0.6720430254936218), ('a', 0.9672043025493621), ('a', 0.6720430254936218), ('a', 0.6720430254936218), ('a', 0.8720430254936218), ('a', 0.6720430254936218), ('a', 0.6720430254936218), ('c', 0.6720430254936218), ('c', 0.6720430254936218), ('c', 0.6720430254936218), ('c', 0.6720430254936218), ('o', 0.6720430254936218), ('o', 0.6720430254936218), ('o', 0.6720430254936218), ('o', 0.7720430254936218), ('o', 0.6720430254936218), ('r', 0.6720430254936218), ('r', 0.6720430254936218), ('r', 0.9720430254936218), ('r', 0.6720430254936218), ('d', 0.6720430254936218), ('i', 0.6720430254936218), ('i', 0.6720430254936218), ('i', 0.6720430254936218), ('n', 0.6720430254936218), ('n', 0.6720430254936218), ('n', 0.6720430254936218),]

simis = []
def end_of_loop():
    raise StopIteration

simis.extend(list(end_of_loop() if item[1]*100 >= 90 else item[1]*100 for item in m))

print(simis)

Technically, that's a generator expression, not a list-comprehension. Regardless, it seems like you just want to find- and append the first item that satisfies a condition, so you'd just use next :

simis.append(next(item for item in m if item[1]*100 >= 90)[1]*100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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