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.
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.
You can use tuple for doing that job like this:
[(print("bla1"), print("bla2")) for i in list]
it's work correctly.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With