pythonic学习_学习pythonic编码风格的思考过程

pythonic学习

If you are not aware of what is Pythonic way and why it is important then, please invest little time with this blog(Link given below).

如果您不了解什么是Python方式以及为何如此重要,请花一点时间在此博客上(下面提供链接)。

I have accumulated some random examples so you can skip if you already do use of that way in your code.

我已经积累了一些随机的示例,因此如果您已经在代码中使用过这种方式,则可以跳过。

First of all, I would like to mention a few Python topics which are more important to do code in a Pythonic way and few suggestions that help you to think to optimize the code to make to more Pythonic.

首先,我想提及一些Python主题,这些主题对于以Pythonic方式进行代码更重要,而一些建议则可以帮助您思考如何优化代码以使其更适合Pythonic。

  • Use Python built-in functions.

    使用Python内置函数。
  • Use the Python advance modules and libs for example collections, lambda, etc.

    将Python高级模块和库用于示例集合,lambda等。
  • Learn Comprehension with iterators.

    通过迭代器了解理解。
  • Learn lambda expressions functions.

    了解lambda表达式函数。
  • Learn functions in python more, like functions as an object and its features.

    进一步学习python中的函数,例如作为对象的函数及其功能。
  • Learn Generators and Decorators.

    了解生成器和装饰器。
  • See if is built-in functions that create a new copy of iterators and decide when to use those built-in functions.

    查看是否有内置函数创建新的迭代器副本并确定何时使用这些内置函数。
  • Optimize the loops and conditional statements.

    优化循环和条件语句。
  • Always think about selecting the correct iterator object for the logic.

    始终考虑为逻辑选择正确的迭代器对象。
  • Try to find out a way to reduce lines of code.

    尝试找出减少代码行的方法。
  • Only think of reducing lines of code to make it more understandable. (Too much on this will again make it more complex to understand and less Pythonic).

    只考虑减少代码行以使其更易于理解。 (太多的事情将再次使它变得更复杂,而Pythonic也更少)。
  • Use PEP 8 guidelines to write the code.

    使用PEP 8准则编写代码。
  • Break the main logic in functions to make code more understandable.

    打破函数的主要逻辑,使代码更易于理解。

Let’s see the examples, Please try writing the code by putting your thoughts in It, so that It will be more easy and clear to understand.

让我们看一下示例,请尝试将您的想法写在其中,以使代码更容易理解。

空列表检查没有大小比较: (The Empty list checks without a size compare:)

numbers = [1, 2, 3, 4, 5]
if numbers:

使用sorted()和list.sort()函数: (Use of sorted() and list.sort() functions:)

The difference between sorted() and list.sort() function:

sorted()和list.sort()函数之间的区别:

sorted(): The function returns a new list containing all items from the iterable in ascending order.

sorted():该函数返回一个新列表,其中包含可迭代对象中所有项目的升序排列。

l = [1, 2, 3, 4, 5] 
new_l = sorted(l)
print(new_l)
print(l)

list.sort(): The functions will not create a new list It modifies the same list on which it is called.

list.sort():这些函数将不会创建新列表。它会修改调用该列表的相同列表。

l = [1, 2, 3, 4, 5] 
l.sort()
print(l)

必须使用内置功能: (Must use built-in functions:)

all(): The function returns True if all items in an iterable are true, otherwise it returns False.

all():如果iterable中的所有项目均为true,则该函数返回True ,否则返回False。

any(): The function returns True if any item in an iterable is true, otherwise it returns False.

any()如果iterable中的任何一项为true,则该函数返回True ,否则返回False。

# all()
l = [0, 1, 1]
res = all(l)
print(res)# any()
s = {0, 1, 0}
res = any(s)
print(res)

filter(): The function returns an iterator where the items are filtered through a function to test if the item is accepted or not.

filter()该函数返回一个迭代器,在该迭代器中通过函数对项目进行过滤以测试该项目是否被接受。

numbers = [1, 2, 3, 4, 5, 6]
def ev_odd(x):
if x % 2 == 0:
return True
else:
return Falseres = filter(ev_odd, numbers)
print(res) # object
print(list(res)) # converting into list

hash(): The function returns the hash value of a specified object.

hash():该函数返回指定对象的哈希值。

t1 = (1, 2, 3, 4)
t2 = (1, 2, 3, 4)
print(hash(t1))
print(hash(t2))

An object is hashable if it has a hash value which never changes during its lifetime, All of Python’s immutable built-in objects are hashable.

如果对象的哈希值在其生命周期内始终不变,则该对象是可哈希的。所有​​Python不变的内置对象都是可哈希的。

map(): The function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

map():该函数为Iterable中的每个项目执行一个指定的函数。 该项目将作为参数发送到函数。

def add(a, b):
return a + bdef increase(a):
return a + 1res = map(add, [1, 2, 3], [1, 2, 3])
print(list(res))
res = map(increase, [1, 2, 3])
print(list(res))

max(): The function returns the item in an iterable with the highest value.

max():此函数以最大的可迭代值返回项目。

min(): The function returns the item in an iterable with the smallest value.

min():该函数以最小的迭代值返回该项目。

print(max([1, 4, 5, 8, 3, 9, 10]))
print(max("ABCDEFG"))
print(min([1, 4, 5, 8, 3, 9, 10]))
print(min("ABCDEFG"))

reversed(): The function returns a reversed iterator object created newly without modifying the original iterator object.

reversed():该函数返回一个新创建的反向迭代器对象,而无需修改原始迭代器对象。

list.reverse(): The functions modify the same iterator object in reverse order.

list.reverse()函数以相反的顺序修改同一迭代器对象。

l = [1, 4, 5, 8, 3, 9, 10]
l.reverse()
print(l)
res = reversed(l)
print(list(res))

enumerate(): The functions give touples with index values.

enumerate():这些函数提供带有索引值的小插图。

l = ['mark', 'jake', 'part']for data in enumerate(l):
print(data)

理解与Lambda (Comprehension & Lambda)

Comprehensions are constructs that allow sequences to be built from other sequences. Python 2.0 introduced list comprehensions and Python 3.0 comes with a dictionary and set comprehensions.

理解是允许从其他序列构建序列的构建体。 Python 2.0引入了列表推导Python 3.0附带了字典和set推导

Iterating through a string Using List Comprehension:

使用列表理解遍历字符串:

alfa = [letter for letter in 'ABCDEFGHIZKLMNOPQRSTUVWXYZ']
print( alfa)

List Comprehension is not the only way to work with a list in Python, Python has lambda and related built-in functions.

列表理解不是在Python中使用列表的唯一方法,Python具有lambda和相关的内置函数。

Sometimes List Comprehension and sometimes using lambda functions looks more or less Pythonic in writing. we can choose the way which makes code more understandable.

在编写时,有时列表理解有时使用lambda函数看起来或多或少是Pythonic的。 我们可以选择使代码更易于理解的方式。

Code example for the above string iteration with lambda functions.

上述带有lambda函数的字符串迭代的代码示例。

alfa = list(map(lambda x: x, 'ABCDEFGHIZKLMNOPQRSTUVWXYZ'))
print(alfa)

lambda与列表理解的条件 (Conditions with lambda vs List Comprehension)

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = [x for x in l if x % 2 == 0]
print(even)
even = list(filter(lambda x: x % 2 == 0, l))
print(even)

List comprehension sometimes is a perfect replacement for loops, lambda function as well as the functions map(), filter(), and reduce(). As I mention using comprehension and lambda both are Pythonic but It will be based on the requirement of logic. we can write the code which is easier understandable.

列表理解有时是循环,lambda函数以及map(),filter()和reduce()函数的完美替代。 正如我提到的,使用comprehension和lambda都是Pythonic的,但这将基于逻辑需求。 我们可以编写更容易理解的代码。

优化循环和条件语句 (Optimize the loops and conditional statements)

For the conditional statement, we can avoid more nesting of if-else “{ if { if {}}}” statements by writing them in a single line if possible.

对于条件语句,如果可能,可以通过在一行中编写来避免if-else “ {if {if {if {}}}”语句的更多嵌套。

Optimizing loops according to me is using comprehension and lambda expressions with a map, filter, and reduce functions for performing iteration.

根据我的说法,优化循环是将推导和lambda表达式与map,filter和reduce函数一起使用,以执行迭代。

As I have given examples above for map and filter functions, the reduce() function belongs to from functools module see the use of reduce function below.

正如我上面给出的有关map和filter函数的示例一样,reduce()函数属于functools模块,请参见下面的reduce函数的用法。

import functools
numbers = [1, 3, 5, 6, 2]
print(functools.reduce(lambda a, b: a+b, numbers))

This topic has full python to explore and learn so I am stopping here, I hope the article gives a thought process by the above-written points so explore more and learn more.

本主题有完整的python可供探索和学习,所以我在这里停止,希望本文根据上述要点给出一个思考过程,以便进一步探索和了解更多。

Happy coding!! thanks

编码愉快!! 谢谢

翻译自: https://medium.com/swlh/a-thought-process-to-learn-the-pythonic-coding-style-5e34d3c18dd3

pythonic学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值