Python“其他所有元素";成语 [英] Python "Every Other Element" Idiom

查看:42
本文介绍了Python“其他所有元素";成语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我花了很多时间用Python编写代码,但没有足够的时间来创建Pythonic代码.最近,我遇到了一个有趣的小问题,我认为这可能是一个简单而惯用的解决方案.简而言之,我需要收集列表中的每个顺序对.例如,给定列表 [1,2,3,4,5,6] ,我想计算 [(1,2 ,,(3,4),(5,6)] .

I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list [1,2,3,4,5,6], I wanted to compute [(1,2),(3,4),(5,6)].

当时我想出了一个快速的解决方案,看起来像是翻译过的Java.再问这个问题,我能做的最好的是

I came up with a quick solution at the time that looked like translated Java. Revisiting the question, the best I could do was

l = [1,2,3,4,5,6]
[(l[2*x],l[2*x+1]) for x in range(len(l)/2)]

具有在长度不均的情况下扔掉最后一个数字的副作用.

which has the side effect of tossing out the last number in the case that the length isn't even.

我是否缺少一种惯用的方法,或者这是我所能得到的最好的方法?

Is there a more idiomatic approach that I'm missing, or is this the best I'm going to get?

推荐答案

这样做会更加整洁:

>>> data = [1,2,3,4,5,6]
>>> zip(data[0::2], data[1::2])
[(1, 2), (3, 4), (5, 6)]

(但是,如果您不熟悉范围的跨距"功能,那么它的可读性可能会降低).

(but it's arguably less readable if you're not familiar with the "stride" feature of ranges).

就像您的代码一样,它会丢弃您拥有奇数个值的最后一个值.

Like your code, it discards the last value where you have an odd number of values.

这篇关于Python“其他所有元素";成语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆