pythonic_您绝对应该知道的完全Pythonic Python的东西

pythonic

Most of us have some go-to functions when we code. Once we are used to coding in a certain way, we tend to use the same functions over and over again, even when there may be a much better way. And, as per the Zen of Python, there should be only one — and preferably only one — obvious way to do it!

我们的M个OST有一些去到功能,当我们的代码。 一旦习惯了某种编码方式,即使有更好的方法,我们也会一遍又一遍地使用相同的功能。 并且,按照Python的Zen, 应该只有一种-最好只有一种-显而易见的方法!

More often than I would like to admit, I have fallen in this trap as well. For example getting too used to for loops, using prints too often instead of logs and the list goes on. That is definitely not the Pythonic way to do it. You can always refresh your knowledge about being Pythonic, i.e. writing clear, concise and easy to maintain codes and much more here:

比起我想承认的更多,我也陷入了这个陷阱。 例如,对于循环来说太习惯了,过于频繁地使用打印而不是日志,列表就继续存在。 这绝对不是Python的方法。 您始终可以刷新有关Python语言的知识,即编写清晰,简洁且易于维护的代码,以及更多内容:

Over a period, the following 7 functionalities became my favorites to use because of their simplicity and an inherent elegance. If you haven’t till now, you should definitely try to use them whenever possible.

在一段时间内,以下7种功能因其简单性和固有的优雅性而成为我的最爱。 如果您到目前为止还没有,那么绝对应该尝试尽可能使用它们。

1. f-Strings

1. f弦

Python 3.6 came up with a brilliant way to format strings known as f-strings (formatted string literals). Before f-strings in Python 3, we could do it in any of the following two ways:

Python 3.6提出了一种出色的方式来格式化称为f字符串(格式化的字符串文字)的字符串。 在Python 3中使用f-strings之前,我们可以通过以下两种方式之一进行操作:

# Method_1 Using %s>> name = "Leonardo"
>> surname = "Da Vinci"
>> Occupation_1 = "Artist"
>> Occupation_2 = "Inventor"
>> Occupation_3 = "Scientist"
>> Occupation_4 = "Mathematician"
>> Occupation_5 = "Philosopher">> print ("%s %s was an %s, %s, %s, %s and %s." % (name, surname, Occupation_1, Occupation_2, Occupation_3, Occupation_4, Occupation_5))'

As we can see, the readability of the code is totally screwed up. As is the case with str.format() below.

如我们所见,代码的可读性被完全搞砸了。 与下面的str.format()一样。

# Method_2 Using str.format()>> print (("{name} {surname} was an {Occupation_1}, {Occupation_1}, {Occupation_1}, {Occupation_1} and {Occupation_1}.").format(name = name, surname = surname, Occupation_1 = Occupation_1, Occupation_2 = Occupation_2, Occupation_3 = Occupation_3, Occupation_4 = Occupation_4, Occupation_5 = Occupation_5))'

This is in no way better that the first. Fortunately, we have Python 3 f-strings to the rescue. Here is how they work:

这绝对比第一个更好。 幸运的是,我们有了Python 3 f字符串来解救。 它们的工作方式如下:

>> f'{name} {surname} was an {Occupation_1}, {Occupation_2}, {Occupation_3}, {Occupation_4} and {Occupation_5}.''

As simple as that! And boy, do we have readability. To top it all, since f-strings are evaluated at runtime, you can do a whole range of things including other functions and methods. Have a look here:

就如此容易! 和男孩,我们有可读性。 最重要的是,由于f字符串是在运行时求值的,因此您可以做很多事情,包括其他函数和方法。 在这里看看:

>> f'{2*3}'
>> '6'
'leonardo'

I know there are conservative python pundits out there who would quote the Zen of Python and say that f-strings are un-pythonic as there should be only one obvious way to do things. And, in this case there are two. But practicality beats purity and readability counts. I have now found just one obvious way to do it, that’s f-strings!

我知道那里有一些保守的python专家会引用Python的Zen,并说f字符串是非Python的 ,因为应该只有一种明显的做事方法。 并且,在这种情况下,有两个。 但是实用性超过了纯度和可读性。 我现在发现只有一种明显的方法可以做到这一点,那就是f弦!

2. Lists and Dictionaries (Packing, Unpacking)

2.清单和字典(包装,拆箱)

Lists and dictionaries are two of the most used objects in python, especially if you are into data wrangling and analysis. They are also that much confusing to use. It is extremely important to use them in a lean way. In this case, we unleash the power of * and ** as the important arguments associated with lists and dictionaries for creating functions.

列表和字典是python中两个最常用的对象,尤其是在您进行数据整理和分析时。 它们使用起来也很混乱。 精简使用它们非常重要。 在这种情况下,我们释放*和**的功能作为与创建函数的列表和字典相关的重要参数。

>> def some_function (a,b,c,d):
print (a,b,c,d)>> some_list = [1,2,3,4]
>> some_dictionary =

Now let’s check out how unpacking works for the above:

现在,让我们检查一下上述情况的拆包工作原理:

# Unpacking list>> TypeError: 

As you see, it naturally considers the list as one positional argument. In order to do this correctly you use a * before the list and voila:

如您所见,它自然会将列表视为一个位置参数。 为了正确执行此操作,请在列表之前使用*,然后瞧瞧:

# Unpacking list>> 1 2 3 4

Similarly, for dictionaries, it is **.

同样,对于字典,它是**。

# Unpacking dictionary>> 1 2 13 14

It must be noted that the dictionary keys are matched with the function, if the keys were different, you would get an error.

必须注意,字典键与功能匹配,如果键不同,则会出现错误。

# Unpacking dictionary>> some_dictionary_2 = 
>> TypeError:

Let us see how packing works. For lists we can use pack arguments (args) with a *. In the same way, for dictionaries we use ** to pack key word arguments (kwargs).

让我们看看包装是如何工作的。 对于列表,我们可以使用带有*的pack参数(args)。 同样,对于字典,我们使用**打包关键字参数(kwargs)。

# List Packing>> def*args):
args =

args[0] =
args[1] = >> some_list_packing('I am packing','','','')I am about to pack lists# Dictionary Packing>>> def some_dictionary_packing(**kwargs):>>> for key in kwargs: print(f'{key} = {kwargs[key]}')
# See how I used the f-string there?>>> some_dictionary_packing(a= "I", b= "am", c= "about", d= "to write..")
a = I
b = am
c = about
d = to write..

As you can notice, packing and unpacking of lists and dictionaries is exceptionally easy and can simplify your code a lot!

如您所见,列表和字典的打包和拆包非常容易,并且可以大大简化您的代码!

3. Dynamic New Type

3.动态新类型

I know it sounds like the latest trending fashion, in Python it is way cooler. Did you know that Python allows you to create classes on the go with ‘type’? Here is how it is done and it is more awesome than you can imagine:

我知道这听起来像是最新的流行趋势,但是在Python中却凉爽得多。 您是否知道Python允许您使用'type'随时创建类? 这是完成的过程,它比您想象的还要强大:

>>> NewClass = type("NewClass", (object,), {"intro": "This is an awesome new class"})>>> n = NewClass()
>>> n.intro"This is an awesome new class"

which is exactly the same as:

完全相同:

>>> class NewClass(object):
intro = "This is an awesome new class"
>>> n = NewClass()
>>> n.intro"This is an awesome new class"

Of course, I have simplified the example here for your easier understanding of the great power of dynamic classes. You can really create advanced classes with ease using this functionality.

当然,为了简化您对动态类的强大功能的理解,我在这里简化了示例。 使用此功能,您确实可以轻松地创建高级类。

4. Try Except

4.尝试除

I cannot enumerate the number of times I have been thankful to the python gods for creating this. It tests a code block and allows us to handle errors in a simple and effective way!

我无法列举我一直感谢python神创造这个的次数。 它测试代码块,并允许我们以简单有效的方式处理错误!

# use the unpacking lists function again for the example>> def some_function (a,b,c,d):
print (a,b,c,d)a_list = [1,2,3,4]>> try:

except:
print(“Put * before the input list in the function”)
Put * before the input list in the function

When your code becomes larger, it becomes pertinent that you use this more often along with the logging functionality. In any case, never do the following:

当您的代码变大时,变得更有意义的是您将其与日志记录功能一起更频繁地使用。 无论如何,决不要执行以下操作:

>> try:

except:
pass

The Python Gods will never forgive you for that!

Python Gods永远不会原谅您!

5. Mutable Defaults

5.可变默认值

This is a nifty little trick that has more benefits than it appears to have and a bigger potential for errors if not followed correctly than you initially imagine. Here is a code sample to make you see what I mean:

这是一个漂亮的小把戏,它带来的好处多于看上去的好处,而且如果未按照您最初的想象正确进行操作,则出错的可能性更大。 这是一个代码示例,使您明白我的意思:

>>> def something(x=[]):
x.append(1)
print (x)
>>> something()
[1]>>> something()
[1, 1]>>> something()
[1, 1, 1]

You see, the list gets appended every time you use this function. Instead, you should use a default value denoting "not indicated" and replace with the mutable you'd like as default:

您会看到,每次使用此功能时,列表都会被追加。 相反,您应该使用表示“未指示”的默认值,并替换为您想要的默认可变项:

>>> def something(x= None):
if x is None:
x= []
x.append(1)
print (x)>>> something()
[1]
>>> something()
[1]

Trust me, knowing how to use mutable default arguments beforehand will save you a lot of painful hours of debugging!

相信我,事先知道如何使用可变的默认参数将为您节省大量的调试时间!

6. Value Swapping

6.价值交换

I vaguely remember that when I learned Java, the basics that we were introduced to swapping values was to create a third temporary variable.

我隐约记得,当我学习Java时,被引入交换值的基础知识是创建第三个临时变量。

a = 1, b =2. Wanna swap values? Create a temporary variable c. Then c = a, a = b and b = c. How annoying! Here’s how it would look in Java:

a = 1,b = 2。 想交换价值吗? 创建一个临时变量c。 那么c = a,a = b和b = c。 真烦人! 这是在Java中的外观:

void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
// a and b are copies of the original values.
}

Well, we have python tuples to the rescue. Why create a third variable when we can swap them in place!

好吧,我们有python元组可以解救。 当我们可以交换它们时,为什么还要创建第三个变量!

>> a = 10
>> b = 5
>> a, b = b, a
>> print(a)
5>>
10

It is not a huge deal, but sometimes, knowing the simple basics can help us a lot in the long run.

这不是什么大问题,但是有时候,了解简单的基础知识从长远来看可以对我们有很大帮助。

7. Replace white spaces with braces?

7.用大括号替换空格?

Yes, folks, you heard that right! All belonging to Java Camp out there, we know you hate the delimiting blocks that are spaces and would love to have those curly brackets. Finally, there is a way:

是的,伙计们,你没听错! 所有这些都属于Java Camp,我们知道您讨厌空格的分隔块,并且希望使用大括号。 最后,有一种方法:

from __future__ import braces

from __future__ import braces

Once you run the above, you get

运行上面的内容后,您将获得

SyntaxError: not a chance

SyntaxError: not a chance

Gotcha! That’s never gonna happen. So long suckers!

知道了! 那永远不会发生。 这么长的吸盘!

Image for post
Pixabay Pixabay

Excuse me for delineating and starting this subsection with an Easter Egg, I couldn’t help myself.

对不起,我用复活节彩蛋来描述和开始本小节,我无能为力。

But the __future__ module is more helpful than you might imagine. For real this time! It helps in compatibility with latest versions of python. Take for example here:

但是__future__模块比您想象的要有用。 这次真的! 它有助于与最新版本的python兼容。 以这里为例:

If you are using Python 2.7

如果您使用的是Python 2.7

a = 1000print a>> 1000

Now, you can import the print function from the latest Python version.

现在,您可以从最新的Python版本导入打印功能。

>> from __future__ import print_function>> print aSyntaxError: Missing parentheses in call to ‘print’. Did you mean print(a)?>> print (a)1000

The future module has a whole range of functions included. You can check it out here:

未来的模块包含了全部功能。 您可以在这里查看:

That’s it folks! The listing above contains only a few of the many elegant functionalities available in Python. I hope you found them useful, your coding peers will definitely find your code easier to review if you apply these.

就是这样! 上面的清单仅包含Python中许多优雅的功能中的几个。 我希望您发现它们有用,如果您应用它们,您的编码同行一定会发现您的代码更易于查看。

Happy Coding!

编码愉快!

翻译自: https://towardsdatascience.com/perfectly-pythonic-python-stuff-that-you-should-definitely-know-daa559528d58

pythonic

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值