简体   繁体   English

Python样式 - 在十进制后添加0

[英]Python Style - Adding 0 After Decimal

I had a question regarding Python code style. 我有一个关于Python代码风格的问题。 I couldn't find an answer on PEP 8 and decided to ask here. 我在PEP 8找不到答案,于是决定在这里问。

I've noticed in many cases when expressing floating-point numbers people omit the trailing 0. For example: 我注意到在许多情况下,当表达浮点数时,人们会忽略尾随0。例如:

# List containing floating point numbers.
a = [0., 1., 2., 3.]

However, I've always found it convenient and clearer to add the extra 0 like so: 但是,我总是发现添加额外的0更方便,更清晰:

a = [0.0, 1.0, 2.0, 3.0]

Is there a standard for this, or should I just go with whatever is the least ambiguous? 是否有一个标准,或者我应该选择最不模糊的东西?

Some languages, notably Python have rules for what should be well written code . 有些语言,特别是Python有适当编写代码的规则。 For Python, PEP-8 is the reference, which allows various programmers to easily read code written by others provided PEP-8 is respected. 对于Python,PEP-8是参考,它允许各种程序员轻松读取其他人编写的代码,只要PEP-8得到尊重。

Here you are in a case that is not covered by PEP-8. 在这里,您处于PEP-8未涵盖的案例中。 So you just have to apply the good old rule: choose one convention among a project or team and stick to it. 所以你只需要应用好的旧规则:在项目或团队中选择一个约定并坚持下去。

If you work alone and prefere adding a 0, just do it. 如果你单独工作并且喜欢添加0,那就去做吧。 If you work in a team, speak of that with your fellows, and choose one convention for all of you. 如果您在团队中工作,请与您的同事谈谈,并为所有人选择一个约定。 If you edit existing code where a convention is used, stick to the existing convention. 如果编辑使用约定的现有代码,请坚持使用现有约定。

What I use is opinion only and has not to be in a SO answer. 使用的只是意见,而不是一个SO答案。

In PEP 20 it says that "readability counts". PEP 20中,它表示“可读性很重要”。

In this example it is easier to read the second version than the first. 在此示例中,第二个版本比第一个版本更容易阅读。 For example if these were longer lists it would be harder to determine if the first list is a list of floats or floats and integers. 例如,如果这些是较长的列表,则更难确定第一个列表是浮点数,浮点数和整数列表。

With the first example if a decimal point was missing this may not be obvious. 对于第一个例子,如果缺少小数点,这可能并不明显。

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

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