简体   繁体   English

python:以更好的方式编写代码?

[英]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 谢谢大家

You can use zip function : 您可以使用zip函数:

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

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. 只是为了解释, zip内置函数接受两个或多个可迭代对象,并为每个可迭代对象生成一个包含当前项目的元组,直到达到最小长度的可迭代对象的末尾。

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 FWIW,您可以将括号放在

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

And since you're not using x it's common to replace it with underscore: 而且由于您没有使用x所以通常用下划线替换它:

z = [y for _,y in array]
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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM