Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple actions in list comprehension python

I would like to know how to perform multiple commands in a list comprehension.

Can you give me an example for something simple like:

[print ("bla1") and print ("bla2") for i in list]

so for a list of 4 length 4 I would have:

bla1
bla2
bla1
bla2
bla1
bla2
bla1
bla2

Dtrangely enough I didn't easily find it in the documentation. (If you can see an obvious reason why I didn't and can let me know how should I search for such stuff that would be even better).

EDIT: OK, that was a very bad example according to comments. I am interested in creating a new from an old one but I feel that I need two commands to do that. (not a simple print, of course). For example. I have a list of lists, and I want to create a list that is a result of manipulation of the sublists.

like image 412
Lost_DM Avatar asked Oct 07 '11 14:10

Lost_DM


4 Answers

Don't use list comprehension for commands. List comprehensions are for creating lists, not for commands. Use a plain old loop:

for i in list:
    print('bla1')
    print('bla2') 

List comprehensions are wonderful amazing things full of unicorns and chocolate, but they're not a solution for everything.

like image 152
Petr Viktorin Avatar answered Oct 09 '22 14:10

Petr Viktorin


You can use tuple for doing that job like this:

[(print("bla1"), print("bla2")) for i in list]

it's work correctly.

like image 36
Ahad aghapour Avatar answered Oct 09 '22 13:10

Ahad aghapour


In some cases, it may be acceptable to call a function with the two statements in it.

def f():
   print("bla1")
   print("bla2")

[f() for i in l]

Can also send an argument to the function.

def f(i):
   print("bla1 %d" % i)
   print("bla2")

l = [5,6,7]

[f(i) for i in l]

Output:

bla1 5
bla2
bla1 6
bla2
bla1 7
bla2
like image 11
plafratt Avatar answered Oct 09 '22 12:10

plafratt


If "I need two commands" means that there are two functions, they must be related in some way.

def f( element ):
    return intermediate

def g( intermediate ):
    return final

new_list = [ g(f(x)) for  x in old_list ]

If that's not appropriate, you'll have to provide definitions of functions which (a) cannot be composed and yet also (b) create a single result for the new sequence.

like image 4
S.Lott Avatar answered Oct 09 '22 14:10

S.Lott