Using break in a list comprehension
even = [n for n in numbers[:None if 412 not in numbers else numbers.index(412)] if not n % 2]
Just took F.J.'s code above and added a ternary to check if 412 is in the list. Still a 'one liner' and will work even if 412 is not in the list.
break inside list comprehension
use any()
with a generator
filterList=['test','2','x','123','orange']
print ([i for i in datalist if any(j for j in filterList if j in i) ])
any
stops the iterations when the first element is found
list comprehension with if and break
You can create a filtered new list based on your keyword search in a second list using any
:
>>> [x for x in queries.split(',') if any(kw in x for kw in keywords)]
['watch movie online', ' movie poster', ' course of events', ' movie in this summer', ' python course', ' watch movie about training course']
The break
is naturally in any
since it will short-circuit on the first True and break out of the loop over keywords
.
Then print the new list or sequence using '\n'.join(iterable)
to get the effect of printing each element in the loop.
>>> print ('\n'.join(x for x in queries.split(',') if any(kw in x for kw in keywords)))
watch movie online
movie poster
course of events
movie in this summer
python course
watch movie about training course
In that case, you can use a generator vs a list comprehension.
However, don't be afraid of just using a loop in Python; they are easy to understand and obvious in intent.
(And your can strip the space on the elements using .lstrip(x)
if desired.)
list comprehensions with break
You can't really break a list comprehension's internal for loop, what you can do is avoid having to break it at all by using the next function to find the first occurrence of a matching value:
list1 = [4, 5, 6, 9, 10, 16, 21, 23, 25, 27]
list2 = [1, 3, 5, 7, 8, 11, 12, 13, 14, 15, 17, 20, 24, 26, 56]
list3 = [ next(j for j in list2 if j>i) for i in list1 ]
output:
print(list1)
print(list3)
[4, 5, 6, 9, 10, 16, 21, 23, 25, 27]
[5, 7, 7, 11, 11, 17, 24, 24, 26, 56]
If you are concerned about performance (since the list comprehension will be slower than the loops), you could use a bisecting search in list 2 to find the next higher value:
from bisect import bisect_left
list3 = [ list2[bisect_left(list2,i+1)] for i in list1 ]
This assumes that list2 is sorted in ascending order and that max(list2) > max(list1)
Using next instead of break in comprehension list
You could pass a default argument in next()
.And next()
would only return only one element,so "".join([])
is unnecessary.
Code below:
key = next((key for key, value in substitution_dict.items() if word == key or word in value), None)
When the iterator is exhausted, it would return None
.
Or if you really want to use it with ''.join
, like:
key = "".join([next((key for key, value in substitution_dict.items() if word == key or word in value), "")])
Related Topics
Remove Quotes from String in Python
Prepend a Line to an Existing File in Python
Dangers of Sys.Setdefaultencoding('Utf-8')
How to Change Index of a for Loop
Trying to Import Module with the Same Name as a Built-In Module Causes an Import Error
Two Variables in Python Have Same Id, But Not Lists or Tuples
Is There a Matplotlib Equivalent of Matlab's Datacursormode
How to Put Multiple Statements in One Line
Url Query Parameters to Dict Python
Check If a File Is Not Open Nor Being Used by Another Process
Prime Number Check Acts Strange
Pandas "Can Only Compare Identically-Labeled Dataframe Objects" Error
How to Escape Special Characters of a String with Single Backslashes
Python Enum, When and Where to Use
Interactive Input/Output Using Python
Unpacking a List/Tuple of Pairs into Two Lists/Tuples
Reading a Text File and Splitting It into Single Words in Python