Let's say we have a list mylist = ['a', 'b', 'c']
, and we want to generate another list like this: ['a:1', 'a:2', 'b:1', 'b:2', 'c:1', 'c:2']
, which basically appends ':1'
and ':2'
to each element of mylist
.
I wonder how to do this efficiently using list comprehension, if possible?
List comprehension works with string lists also. The following creates a new list of strings that contains 'a'. Above, the expression if 'a' in s returns True if an element contains a character 'a'. So, the new list will include names that contain 'a'.
We can also use assignment expressions in list comprehensions. List comprehensions allow you to build lists succinctly by iterating over a sequence and potentially adding elements to the list that satisfy some condition.
List Comprehension Python Vs. In Python, we also use Lambda functions to modify and manipulate lists. Lambda functions are also known as anonymous functions. Lambda functions are usually used with various built-in functions such as map() filter(), and reduce() to work on lists.
Graphical representation of list comprehension vs lambda + filter. As we can see from the graph that overall list comprehension is much faster than the filter function.
Like this:
['%s:%d' % (e, i) for e in mylist for i in (1, 2)]
I think the most efficient way to do this is with itertools.product
:
http://docs.python.org/2/library/itertools.html#itertools.product
from itertools import product
mylist = ['a', 'b', 'c']
mysuffixes = [':1', ':2']
result = [x+y for x, y in product(mylist, mysuffixes)]
The exact construction might vary depending on how your constants are defined.
>>> a=['a','b','c']
>>> b=[1,2]
>>> import itertools
>>> ['%s:%s' % (x,y) for x,y in itertools.product(a,b)]
['a:1', 'a:2', 'b:1', 'b:2', 'c:1', 'c:2']
In [4]: mylist = ['a', 'b', 'c']
In [5]: list(itertools.chain.from_iterable([[e+":1", e+":2"] for e in mylist]))
Out[5]: ['a:1', 'a:2', 'b:1', 'b:2', 'c:1', 'c:2']
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