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 did开发者_运维知识库n'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.
List comprehensions are only for generating data in list form, not for executing statements (or any other side effect, like writing to a file) multiple times. Use a
for
look for that.Assuming you want to generate a list
['bla1', 'bla2', 'bla1', ...]
: You can't do it in general, each iteration puts a single result value into the list. That value may be a list itself, but then you have a list of lists.In specific cases like your example, it's possible though: Use
['bla' + str(i + 1) for x in list for i in range(2)]
, which iterates overrange(2)
for everyx in list
, and thus generates two values per item inlist
. (list
is a bad name for a variable though, as it's already taken by the builtin.)
Use list comprehension only for creating lists. Your example doesn't use the values of your list at all.
According to the docs:
"List comprehensions provide a concise way to create lists from sequences."
for i in range(len(your_list)):
print "blah1"
print "blah2"
In the above program, we didn't even care about the values in the list. If you were looking for a different application of list comprehension than what you stated in your problem, then do post.
For what it worth it is possible to use list.append in the list comprehension to produce a new list while ignoring the primary output of the list comprehension. The OP mentions a list of lists. Take for example:
>>> master = [range(x,x+2) for x in range(10)]
>>> master
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10]]
Then create a new list by manipulating each sublist (as the OP described in the edit)
>>> new_list = []
>>> [[new_list.append(l[0]*l[1]),new_list.append(l[0]+l[1])] for l in master]
[[None, None], [None, None], [None, None], [None, None], [None, None], [None, None], [None, None], [None, None], [None, None], [None, None]]
>>> new_list
[0, 1, 2, 3, 6, 5, 12, 7, 20, 9, 30, 11, 42, 13, 56, 15, 72, 17, 90, 19]
This does spit out a redundant list of lists with Nones, but also fills the variable new_list with the product and sum of the sublists.
A list comprehension, and relations ( set comprehenson, dictionary comprehension, generator expression ) are all syntax that enables expression of a loop within a single command. Pedantics who fail to recognise that fact are limiting Python needlessly, and those who preach the gospel of 'best practice' hobble their followers with pointless dogma. It isn't just for sequences anymore! Execute commands all you want, if that is the cleanest solution. Not using the output of the expression ( often a list like [None, None] ) isn't any worse than a temporary 'variable' going out of scope after a method / function is completed.
精彩评论