更好的Python列表命名方式,除了"list"之外 [英] Better Python list Naming Other than "list"

查看:215
本文介绍了更好的Python列表命名方式,除了"list"之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好不要将列表变量命名为"list"吗?由于它与python保留关键字冲突.那么,什么是更好的命名呢? "input_list"听起来有点尴尬.

Is it better not to name list variables "list"? Since it's conflicted with the python reserved keyword. Then, what's the better naming? "input_list" sounds kinda awkward.

我知道它可能是特定于问题的,但是,说我有一个快速排序功能,则quick_sort(unsorted_list)仍然很长,因为传递给排序功能的列表显然没有根据上下文进行排序.

I know it can be problem-specific, but, say I have a quick sort function, then quick_sort(unsorted_list) is still kinda lengthy, since list passed to sorting function is clearly unsorted by context.

有什么主意吗?

推荐答案

我喜欢用其中的复数形式来命名它.因此,例如,如果我有一个名称列表,则将其称为names,然后可以编写:

I like to name it with the plural of whatever's in it. So, for example, if I have a list of names, I call it names, and then I can write:

for name in names:

我认为它看起来不错.但是通常出于您自己的理智,应该为变量命名,以便您可以仅从名称中知道它们的含义.就像Python本身一样,此约定还具有类型不可知的优点,因为names可以是任何可迭代的对象,例如元组,字典或您自己的自定义(可迭代)对象.您可以在任何一个上使用for name in names,并且如果您有一个名为names_list的元组,那将很奇怪.

which I think looks pretty nice. But generally for your own sanity you should name your variables so that you can know what they are just from the name. This convention has the added benefit of being type-agnostic, just like Python itself, because names can be any iterable object such as a tuple, a dict, or your very own custom (iterable) object. You can use for name in names on any of those, and if you had a tuple called names_list that would just be weird.

(在下面的评论中添加:)在某些情况下,您不必这样做.使用i这样的规范变量为短循环建立索引是可以的,因为i通常是这样使用的.如果您的变量在一页以上的代码中使用,以致于无法一次看到其整个生命周期,则应给它取一个明智的名称.

(Added from a comment below:) There are a few situations where you don't have to do this. Using a canonical variable like i to index a short loop is OK because i is usually used that way. If your variable is used on more than one page worth of code, so that you can't see its entire lifetime at once, you should give it a sensible name.

这篇关于更好的Python列表命名方式,除了"list"之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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