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...
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.
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.
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.
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)))
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:
l
that applies an add
function with 1
as an argumentimap()
to produce pairs of x, x+1 valueschain()
and convert it to the list to see the resultIf 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