开发者

Does python have one way of doing things?

I have always seen in python articles/books that python is simple and it has only one way of doing things. I would like someone to explain to me this concept keeping in mind the example below, if I wanted to get the min and ma开发者_高级运维x values of sequence I would do the following;

seq=[1,2,3,4,5,6]

min(seq) #1

max(seq) #6

but I can also do this;

seq[:1]  #1

seq[-1]  #6

surely this are two ways of doing one simple thing. This confuses me a bit.


Not that it "has one way of doing things" as more "There should be one-- and preferably only one --obvious way to do it." (from Zen of Python).

This doesn't exclude possibility of having more than one way of doing things. We're talking about programming where creativity is one of the most important skills and finding new ways of solving problems is a must.

In your example you're doing two different things:

  1. getting minimum and maximum of the list
  2. getting first and the last element of the list

it happens that in this particular case result is exactly the same.


Those are two different things. max() gives you the largest element of the list (using regular number comparison by default), while [-1] gives you the last element – in your example, this happens to be the same thing. But consider this:

>>> seq = [2, 7, 5, 4]
>>> max(seq)
7
>>> seq[-1]
4

BTW, seq[:1] gives you something different again – namely [1] (or [2] in my example), a one-element list. What you probably meant was seq[0], which is the first element of the list, compared to min(seq), the smallest one.


One obvious way.

>>> import this


In your example, you actually do two different things -- they just happen to give the same result, because your input list is sorted. However, there's always multiple ways of doing things. Python's approach isn't really to avoid or forbid multiple ways of doing the same thing, but have one - and preferably only one - obvious way of doing things.


max(), min() and index slicing they all do different things. In your list, the order may not be sorted like your example, so using slicing will not get the max/min for you in those cases. if you want to get max/min values, just use max()/min() functions


There is always more than one way to solve a problem, but the python developers try not to add language features that offer redundant functionality, which is very unlike perl.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜