1

here is an example code

    >>> array = [('The', 'Blue'),('men','Green'),('his','Red'),('beautiful','Yellow')]
    >>> z = [y for (x,y) in array]
    >>> l=[(z[i],z[i+1]) for i in range (len(z)-1)]
    >>> l
    >>> [('Blue', 'Green'), ('Green', 'Red'), ('Red', 'Yellow')]

Is there an alternative way to write this? say, maybe as a one-liner? The above code is better suited from running via a console.

Thanks all

4
  • 1
    I'm voting to close this question as off-topic because it's a better fit for codereview.stackexchange.com Commented Feb 27, 2015 at 12:22
  • @MichaelFoukarakis Thanks for the suggestion! Never knew that codereview existed. Commented Feb 27, 2015 at 12:24
  • 1
    @MichaelFoukarakis Example code is off-topic for Code Review. Commented Feb 27, 2015 at 12:27
  • Looking at the related help section, it seems quite alright. Let's take it to chat maybe. :) Commented Feb 27, 2015 at 12:34

4 Answers 4

3

Pulling all answers here together, this one-liner would work:

a = [('The', 'Blue'),('men','Green'),('his','Red'),('beautiful','Yellow')]

l = [(i[1],j[1]) for i,j in zip(a, a[1:])]

Result:

>>> print(l)
>>> [('Blue', 'Green'), ('Green', 'Red'), ('Red', 'Yellow')]

Just to explain, the zip built-in function takes two or more iterables and yields a tuple with the current item for each iterable, until the end of the iterable with the smallest length is reached.

Sign up to request clarification or add additional context in comments.

2 Comments

That's much easier to read than my one-liner. :) And more efficient.
I agree with @PM2Ring that it is much easier to read. Thanks a lot :)
3

You can use zip function :

>>> array = [('The', 'Blue'),('men','Green'),('his','Red'),('beautiful','Yellow')]
>>> z = [y for (x,y) in array]
>>> zip(z,z[1:])
[('Blue', 'Green'), ('Green', 'Red'), ('Red', 'Yellow')]

Comments

1

This can be done as a one-liner, but it looks pretty ugly.

a = [('The', 'Blue'),('men','Green'),('his','Red'),('beautiful','Yellow')]
l = zip(zip(*a)[1], zip(*a)[1][1:])

Two lines is much better:

colors = zip(*a)[1]
l = zip(colors, colors[1:])

FWIW, you can drop the parentheses in

z = [y for (x,y) in array]

And since you're not using x it's common to replace it with underscore:

z = [y for _,y in array]

1 Comment

Thanks a lot for the underscore tip.
1
array = [('The', 'Blue'),('men','Green'),('his','Red'),('beautiful','Yellow')]    

result = [(array[i][1], array[i+1][1])  for i in xrange(len(array)-1)]    
print result

Yields:

[('Blue', 'Green'), ('Green', 'Red'), ('Red', 'Yellow')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.