Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying constants in list comprehension

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?

like image 874
MLister Avatar asked Sep 04 '13 20:09

MLister


People also ask

Can you do list comprehension with strings?

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'.

Can you assign in list comprehension?

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.

Can we use lambda in list comprehension?

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.

Is list comprehension faster than lambda?

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.


4 Answers

Like this:

['%s:%d' % (e, i) for e in mylist for i in (1, 2)]
like image 97
mata Avatar answered Oct 06 '22 03:10

mata


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.

like image 36
Peter DeGlopper Avatar answered Oct 06 '22 03:10

Peter DeGlopper


>>> 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']
like image 22
Prashant Avatar answered Oct 06 '22 02:10

Prashant


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']
like image 30
inspectorG4dget Avatar answered Oct 06 '22 02:10

inspectorG4dget