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

For example, how to convert [1, 5, 7] to [1,2,5,6,7,8] in python? [x, x + 1 for x in [1,5,7]] cannot work exactly ...

+5
source share
7 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: itertools.chain.from_iterable :

 from itertools import chain l = [1, 5, 7] print(list(chain.from_iterable((x, x + 1) for x in l))) 
+3
source

And you can always compromise 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's going on here:

  • we do an iterator over l that applies add function with 1 as argument
  • we will archive the original list with the iterator returned by imap() to create pairs of x, x + 1 values
  • we flatten the list with chain() and convert it to a list to see the result
+2
source

An easy way to think about the problem is to make a second list of added values ​​and add it to the original list, and then sort it:

 l = [1, 5, 7] m = l + [i+1 for i in l] m.sort() print m # [1, 2, 5, 6, 7, 8] 
+2
source

You can combine some ideas from alecx's answer and what you already had:

 >>> import itertools >>> >>> a = [1, 5, 7] >>> b = ((x, x+1) for x in a) >>> >>> list(itertools.chain(*b)) [1, 2, 5, 6, 7, 8] 

What I've done:

  • Define an expression b a that allows us to have a (something similar) tuple that would look like ((1, 2), (5, 6), (7, 8)) , but without an estimate right away. He would also work with a list.

  • Unpack b in the argument list itertools.chain (). This would be equivalent to itertools.chain((1, 2), (5, 6), (7, 8)) . This function combines its arguments.

  • Use list () to create a list from the return value of the itertools.chain() function, since it is an iterator.

This could also work without an intermediate step:

 >>> import itertools >>> list(itertools.chain(*((x, x+1) for x in [1, 5, 7]))) [1, 2, 5, 6, 7, 8] 

But "Simple is better than complex."

Hope this helps.

I would put more links if I had a great reputation, sorry.

+2
source

Make a generator function that iterates through the list, and in turn returns each element and this element plus one. Iterate over the generator.

 def foo(lyst): for element in lyst: yield element yield element + 1 >>> print(list(foo([1, 5, 7]))) [1, 2, 5, 6, 7, 8] >>> >>> print([element for element in foo([1, 5, 7])]) [1, 2, 5, 6, 7, 8] >>> 
+2
source

You can execute the list comprehension logic using tuples, and then smooth out the resulting list:

[n for pair in [(x, x+1) for x in [1,5,7]] for n in pair]

+1
source

If you just want to fill the list with numbers between the min and max + 1 values, you can use [i for i in range (min(x),max(x)+2)] if x is your list.

0
source

All Articles