kuku
kuku

Reputation: 209

How to write a for loop and multiple if statements in one line?

Is there a way to write something like this in one line?

for x in list: 
   if condition1: 
       (...) 
   elif condition2: 
       (...) 
   else: 
       (...) 

Another way of asking is: Is it possible to combine following list comprehensions?

(...) for x in list

and

123 if condition1 else 345 if condition2 else 0

Upvotes: 1

Views: 6733

Answers (3)

Kamran Khan
Kamran Khan

Reputation: 1

The way to write for loop in a single line, mostly used in Data Science Project, You can use this way, as we have six labeled fake news LIAR:

Labels: ['barely-true' 'false' 'half-true' 'mostly-true' 'pants-fire' 'true'], to represent this as a binary labels:

We use the following way:

labels = [ 1 if lab=='false' or lab=='pants-fire' or lab=='barely_true'  else 0 for lab in df.is_fake]

Another way, the same if-else condition for loop:

labels = [ 1 if lab=='false' else 1 if lab=='pants-fire' else 1 if lab=='barely_true'  else 0 if lab == 'true' else 0 if lab == 'half-true' else 0 for lab in df.is_rumor]

Hope to help many of you, who want to do the same way in many problem-solving.

Upvotes: 0

finefoot
finefoot

Reputation: 11224

What you want to do would almost certainly be considered bad style. Maybe it's an XY problem? In that case, you should open another question with the underlying issue.

If you're sure this is what you want, have a look at the following example, using PEP 308 -- Conditional Expressions :

>>> def f(condition1, condition2):
...     return 1 if condition1 else 2 if condition2 else 3
... 
>>> f(True, False)
1
>>> f(True, True)
1
>>> f(False, True)
2
>>> f(False, False)
3

Subsequently, your example

for x in list: 
   if condition1: 
       (...) 
   elif condition2: 
       (...) 
   else: 
       (...) 

could be written as a list comprehension as follows:

[(...) if condition1 else (...) if condition2 else (...) for x in list]

Upvotes: 2

nexla
nexla

Reputation: 453

use lsit comprehensions

var = [i for i in list if i == something or i == something] more on that here

Upvotes: 1

Related Questions