Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list by mapping an element into multiple elements in python?

Tags:

python

For example, how to convert [1, 5, 7] into [1,2,5,6,7,8] into python? [x, x+1 for x in [1,5,7]] can't work for sure...

like image 998
Nan Hua Avatar asked Aug 30 '16 01:08

Nan Hua


People also ask

How do you map an element to a list in Python?

Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable.

How do you convert a list in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Can you map a tuple?

Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc.


2 Answers

Not sure if this is the best way, but I would do:

l = [1, 5, 7]
print([y for x in l for y in (x, x + 1)])

Another way using itertools.chain.from_iterable:

from itertools import chain
l = [1, 5, 7]
print(list(chain.from_iterable((x, x + 1) for x in l)))
like image 150
Karin Avatar answered Oct 25 '22 00:10

Karin


And you can always overcomplicate the problem with operator, imap(), partial(), izip() and chain():

>>> from itertools import chain, izip, imap
>>> from operator import add
>>> from functools import partial
>>> 
>>> l = [1, 5, 7]
>>>
>>> list(chain(*izip(l, imap(partial(add, 1), l))))
[1, 2, 5, 6, 7, 8]

What happens here:

  • we make an iterator over l that applies an add function with 1 as an argument
  • we zip the initial list with the iterator returned by imap() to produce pairs of x, x+1 values
  • we flatten the list with chain() and convert it to the list to see the result
like image 45
alecxe Avatar answered Oct 24 '22 23:10

alecxe