In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about Python coding should pay attention to what things, the editor thinks it is very practical, so share with you to learn, I hope you can learn something after reading this article, do not say much, follow the editor to have a look.
In the programming process, know more about the language around some knowledge, as well as some skills, you can accelerate to become a good programmer.
For Python programmers, you need to pay attention to the things mentioned in this article. You can also take a look at Zen of Python (Zen of Python), which mentions some precautions and examples to help you improve quickly.
1. Beautiful is better than ugly
To achieve a function: read a column of data, return only an even number and divide by 2. Which of the following code is better?
#-- halve_evens_only = lambda nums: map (lambda I: not 2, filter (lambda I: not I% 2) Nums)) #-def halve_evens_only (nums): return [iUnix 2 for i in nums if not i% 2]
two。 Remember the very simple things in Python
# Exchange the step parameters in the a, b = b, a # slice (slice) operator. (the prototype of the slicing operator in python is [start:stop:step], that is, [start index: end index: step size]) a = [1Magi 2je 3je 4je 5] > > a [:: 2] # data with increments of 2 in the traversal list [1JI 3J5] # Special cases `x [::-1] `is a practical way to realize the reverse order of x > > a [::-1] [5Jing 4je 3jue 2jue 1] # reverse order and slice > > x [::-1] [5Jing 4pm 3jue 2] [5, 3, 1]
3. Do not use mutable objects as default values
Def function (x, l = []): # Don't do this def function (x, l=None): # good way if l is None: l = []
This is because when a def declaration is executed, the default parameters are always evaluated.
4. Use iteritems instead of items
Iteritems uses generators, so iteritems is better when iterating through a very large list.
D = {1: "1", 2: "2", 3: "3"} for key, val in d.items () # build the complete list for key when called, val in d.iteritems () # only call values when requested
5. Use isinstance instead of type
# Don't do this if type (s) = = type (""):... If type (seq) = = list or\ type (seq) = = tuple:. # it should be like this if isinstance (s, basestring):. If isinstance (seq, (list, tuple)):...
For reasons, please see: stackoverflow
Notice that I'm using basestring instead of str, because if a unicode object is a string, I might try to check it. For example:
> print isinstance (a, basestring) True > print isinstance (a, str) False
This is because there are two string types, str and unicode, in versions below Python 3.0.
6. Understand all kinds of containers
Python has a variety of container data types, which, in certain cases, is a better choice than built-in containers such as list and dict.
I'm sure most people don't use it. Some careless people around me may write code in the following ways.
Freqs = {} for c in "abracadabra": try: freqs [c] + = 1 except: freqs [c] = 1
Others will say that here is a better solution:
Freqs = {} for c in "abracadabra": freqs [c] = freqs.get (c, 0) + 1
More specifically, you should use the collection type defaultdict.
From collections import defaultdict freqs = defaultdict (int) for c in "abracadabra": freqs [c] + = 1
Other containers:
Namedtuple () # factory function, used to create a list-like container of tuple subclasses with named fields, allowing any end to quickly attach and retrieve Counter # dict subclasses, for hash object counting OrderedDict # dict subclasses, for storing added command record defaultdict # dict subclasses, for calling factory functions to supplement missing values
7. Magic method for creating classes in Python (magic methods)
_ _ eq__ (self, other) # defines behavior of = = operator _ _ ne__ (self, other) # definition! behavior of = operator _ _ lt__ (self, other) # definition
< 运算符的行为 __gt__(self, other) # 定义 >Behavior of operator _ _ le__ (self, other) # defines the behavior of the = operator
8. Use Ellipsis if necessary (ellipsis "...")
Ellipsis is used to slice high-dimensional data structures. Insert as slice (:) to extend the multidimensional slice to all dimensions. For example:
> from numpy import arange > a = arange (16) .reshape # now that there is a 4-dimensional matrix 2x2x2x2, if you select all the first elements of the 4-dimensional matrix, you can use the ellipsis symbol. > > a [..., 0] .flatten () array ([0,2,4,6,8,10,12,14]) # this is equivalent to > a [:, 0] .flatten () array ([0,2,4,6,8,10,12,14]) these are the things you should pay attention to when Python coding The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.