Python“其他所有元素";成语

编程入门 行业动态 更新时间:2024-10-09 14:28:06
本文介绍了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“其他所有元素";成语

本文发布于:2023-11-30 12:47:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成语   元素   Python   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!