nicki
nicki

Reputation: 187

python: write the code in a better way?

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

Upvotes: 1

Views: 151

Answers (4)

Peter Goldsborough
Peter Goldsborough

Reputation: 1388

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.

Upvotes: 3

Tanveer Alam
Tanveer Alam

Reputation: 5275

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')]

Upvotes: 1

PM 2Ring
PM 2Ring

Reputation: 55469

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]

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

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')]

Upvotes: 3

Related Questions