Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common Pythonic writing methods in Python

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you what are the common Pythonic writing methods in Python, I believe most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

0. The program must be understood before it can be executed by the computer.

"Programs must be written for people to read, and only incidentally for machines to execute."

1. Exchange assignment # # not recommended

Temp = a

A = b

B = a

# # recommendation

A, b = b, Mr. a # becomes a tuple object, and then unpack2. Not recommended by Unpacking##

L = ['David',' Pythonista','+ 1-514,555-1234']

First_name = l []

Last_name = l [1]

Phone_number = l [2]

# # recommendation

L = ['David',' Pythonista','+ 1-514,555-1234']

First_name, last_name, phone_number = l

# Python 3 Only

First, * middle, last = another_list

3. Using the operator in## is not recommended

If fruit = "apple" or fruit = = "orange" or fruit = = "berry":

# multiple judgments

# # recommendation

If fruit in ["apple", "orange", "berry"]:

# using in is more concise

4. String operation # # not recommended

Colors = ['red',' blue', 'green',' yellow']

Result =''

For s in colors:

Result + = s # each assignment discards the previous string object and generates a new object

# # recommendation

Colors = ['red',' blue', 'green',' yellow']

Result = '.join (colors) # No additional memory allocation

5. Dictionary key value list # # not recommended

For key in my_dict.keys ():

# my_ dict[key]...

# # recommendation

For key in my_dict:

# my_ dict[key]...

# only if the key value needs to be changed in the loop, we need to use my_dict.keys ()

# generate a static list of key values.

6. Dictionary key value judgment # # not recommended

If my_dict.has_key (key):

#... do something with d [key]

# # recommendation

If key in my_dict:

#... do something with d [key]

7. Dictionary get and setdefault methods # # not recommended

Navs = {}

For (portfolio, equity, position) in data:

If portfolio not in navs:

Navs [portfolio] =

Navs [portfolio] + = position * prices [equity]

# # recommendation

Navs = {}

For (portfolio, equity, position) in data:

# using the get method

Navs [portfolio] = navs.get (portfolio,) + position * prices [equity]

# or use the setdefault method

Navs.setdefault (portfolio,)

Navs [portfolio] + = position * prices [equity]

8. Judge whether it is true or false # # not recommended

If x = = True:

#....

If len (items)! =:

#...

If items! = []:

#...

# # recommendation

If x:

#....

If items:

#...

9. Traversing lists and indexes # # is not recommended

Items = 'zero one two three'.split ()

# method 1

I =

For item in items:

Print i, item

I + = 1

# method 2

For i in range (len (items)):

Print i, items [i]

# # recommendation

Items = 'zero one two three'.split ()

For I, item in enumerate (items):

Print i, item

10. List derivation # # not recommended

New_list = []

For item in a_list:

If condition (item):

New_list.append (fn (item))

# # recommendation

New_list = [fn (item) for item in a_list if condition (item)]

11. List derivation-nested # # not recommended

For sub_list in nested_list:

If list_condition (sub_list):

For item in sub_list:

If item_condition (item):

# do something...

# # recommendation

Gen = (item for sl in nested_list if list_condition (sl)\

For item in sl if item_condition (item))

For item in gen:

# do something...

twelve。 Loop nesting # # not recommended

For x in x_list:

For y in y_list:

For z in z_list:

# do something for x & y

# # recommendation

From itertools import product

For x, y, z in product (x_list, y_list, z_list):

# do something for x, y, z

13. Try to use generators instead of lists # # not recommended

Def my_range (n):

I =

Result = []

While i

< n: result.append(fn(i)) i += 1 return result # 返回列表 ##推荐 def my_range(n): i = result = [] while i < n: yield fn(i) # 使用生成器代替列表 i += 1 *尽量用生成器代替列表,除非必须用到列表特有的函数。 14. 中间结果尽量使用imap/ifilter代替map/filter##不推荐 reduce(rf, filter(ff, map(mf, a_list))) ##推荐 from itertools import ifilter, imap reduce(rf, ifilter(ff, imap(mf, a_list))) *lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。 15. 使用any/all函数##不推荐 found = False for item in a_list: if condition(item): found = True break if found: # do something if found... ##推荐 if any(condition(item) for item in a_list): # do something if found... 16. 属性(property)##不推荐 class Clock(object): def __init__(self): self.__hour = 1 def setHour(self, hour): if 25 >

Hour >: self.__hour = hour

Else: raise BadHourException

Def getHour (self):

Return self.__hour

# # recommendation

Class Clock (object):

Def _ init__ (self):

Self.__hour = 1

Def _ _ setHour (self, hour):

If 25 > hour >: self.__hour = hour

Else: raise BadHourException

Def _ getHour (self):

Return self.__hour

Hour = property (_ _ getHour, _ _ setHour)

17. Use with to process file opening # # not recommended

F = open ("some_file.txt")

Try:

Data = f.read ()

# other file operations..

Finally:

F.close ()

# # recommendation

With open ("some_file.txt") as f:

Data = f.read ()

# other file operations.

18. Using with to ignore exceptions (Python 3 only) # # not recommended

Try:

Os.remove ("somefile.txt")

Except OSError:

Pass

# # recommendation

From contextlib import ignored # Python 3 only

With ignored (OSError):

Os.remove ("somefile.txt")

19. Using with to handle locking # # is not recommended

Import threading

Lock = threading.Lock ()

Lock.acquire ()

Try:

# Mutual exclusion operation.

Finally:

Lock.release ()

# # recommendation

Import threading

Lock = threading.Lock ()

With lock:

# Mutual exclusion operation.

The above is all the contents of the article "what are the common ways to write Pythonic in Python?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report