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

How to use ternary operator for conditional assignment by Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge of "how to use the ternary operator for conditional assignment in Python". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Tip 1 exchange two numbers on the spot

Python provides an intuitive way to assign and exchange values on a single line. Please refer to the following example.

X, y = 10, 20print (x, y) x, y = y, xprint (x, y) # 1 (10,20) # 2 (20,10)

The assignment on the right is a new meta-multicast seed. The one on the left immediately unpacks that (unreferenced) tuple to the name and.

When the allocation is complete, the new tuple is dereferenced and marked as garbage collection. The exchange of variables also occurs at the end.

Tip 2 compare links to operators.

The aggregation of comparison operators is another technique that sometimes comes in handy.

N = 10 result = 1

< n < 20 print(result) # True result = 1 >

N > 2 + 13 > _ 3 > print _ 3

"_" refers to the output of the last executed expression.

Tip 8 Dictionary / set understanding

Just as we use list derivation, we can also use dictionary / set derivation. They are easy to use and equally effective. This is an example.

TestDict = {I: I * i for i in xrange (10)} testSet = {I * 2 for i in xrange (10)} print (testSet) print (testDict) # set ([0,2,4,6,8,10,12,14,16,18]) # {0: 0,1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Note-the only difference between the two statements. "in addition, to run the above code in Python3, replace with."

Tip 9 debugging scripts

We can set breakpoints in the Python script with the help of the module. Follow the example below.

Import pdbpdb.set_trace ()

We can specify and set breakpoints anywhere in the script. This is very convenient.

Tip 10 set up file sharing

Python allows you to run the HTTP server, which you can use to share files from the server root directory. The following is the command to start the server.

Python 2python-m SimpleHTTPServerPython 3python3-m http.server

The above command starts the server on the default port 8000. You can also use a custom port by passing it as the last parameter to the above command.

Tip 11 check objects in Python

We can check the objects in the Python by calling the dir () method. This is a simple example.

Test = [1,3,5,7] print (dir (test)) ['_ _ add__','_ _ class__','_ _ contains__','_ _ delattr__','_ _ delitem__','_ delslice__','_ doc__','_ eq__','_ format__','_ ge__','_ _ getattribute__','_ _ getitem__' '_ _ getslice__',' _ _ gt__','_ _ hash__','_ _ iadd__','_ _ imul__','_ _ init__','_ _ iter__','_ _ le__','_ _ len__','_ _ lt__','_ mul__','_ ne__','_ new__','_ _ reduce__' '_ _ reduce_ex__',' _ _ repr__','_ _ reversed__','_ _ rmul__','_ _ setattr__','_ _ setitem__','_ _ setslice__','_ sizeof__','_ str__','_ _ subclasshook__', 'append',' count', 'extend',' index', 'insert',' pop', 'remove',' reverse' 'sort'] Tip 12 to simplify if statements

To validate multiple values, we can do this in the following ways.

If m in [1,3,5,7]:

Instead of:

If masks 1 or masks 3 or masks 5 or masks 7:

Alternatively, we can use'{1rect 3pm 5je 7} 'instead of [1rect 3pm 5je 7] as the' in' operator, because 'set' can access each element through O (1).

Tip 13 detect the Python version at run time

Sometimes, if the currently running Python engine is lower than the supported version, we may not want to execute our program. To do this, you can use the following code snippet. It also prints the version of Python currently in use in a readable format.

Import sys#Detect the Python version currently in use.if not hasattr (sys, "hexversion") or sys.hexversion! = 50660080: print ("Sorry, you aren't running on Python 3.5\ n") print ("Please upgrade to 3.5.\ n") sys.exit (1) # Print Python version in a readable format.print ("Current Python version:", sys.version)

Alternatively, you can replace sys. Hexversioncodes = 50660080 with sys.version_info > = (3,5) in the above code. This is the advice of an informed reader.

Output at run time on Python 2.7s.

Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux Sorry, you aren't running on Python 3.5Please upgrade to 3.5.

Output at run time on Python 3.5.

Python 3.5.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0] technique 14 combine multiple strings

If you want to connect all the available tags in the list, see the following example.

> test = ['Like',' Python', 'automation']

Now, let's create a string from the elements in the list given above.

> > print''.join (test) Tip 15 four ways to reverse string/list four ways to reverse the list itself testList = [1mai 3jing5] testList.reverse () print (testList) #-> [5,3,1] reverse for element in reversed when iterating in a loop ([1mem3L5]): print (element) # 1-> 5pointer 2-> 3reply 3-> 1 reverse a string "Test Python" [::-1]

This makes the output "nohtyP tseT"

Use slices to reverse the list [1, 3, 5] [::-1]

The above command outputs [5, 3, 1].

Technique 16 play enumeration

Using the enumerator, it is easy to find the index in the loop.

Testlist = [10,20,30] for I, value in enumerate (testlist): print (I,':', value) # 1-> 0: 10 enumerations-> 1: 20 enumerations-> 2: 30 techniques 17 use enumerations in Python.

We can use the following methods to create an enumeration definition.

Class Shapes: Circle, Square, Triangle, Quadrangle = range (4) print (Shapes.Circle) print (Shapes.Square) print (Shapes.Triangle) print (Shapes.Quadrangle) # 1-> 0 # 2-> 1 # 3-> 2 # 4-> 3 Tip 18 returns multiple values from the function.

There are not many programming languages that support this feature. However, functions in Python do return multiple values.

Please refer to the following example to see how it works.

# function returning multiple values.def x (): return 1, 2, 3, Calling the above function.a, b, c, d = x () print (a, b, c, d)

#-> 1 2 3 4

Tip 19 use the splat operator to unpack function parameters.

The splat operator provides an artistic way to extract the parameter list. For clarity, see the following example.

Def test (x, y, z): print (x, y, z) testDict = {'x stores: 1,'y: 2, 'zem: 3} testList = [10, 20, 30] test (* testDict) test (* * testDict) test (* testList) # 1-> x y z 2-> 1 2 3 3-> 10 20 30 Tips 20 use dictionaries to store switch.

We can make a dictionary to store expressions.

Stdcalc = {'sum': lambda x, y: X + y,' subtract': lambda x, y: X-y} print (stdcalc ['sum'] (9) print (stdcalc [' subtract'] (9) # 1-> 12: 2-> 6 Tip 21 calculates the factorial of any number in a row. Python 2.x.result = (lambda k: reduce (int.__mul__, range (1) (1) (3) print (result) #-> 6Python 3.x.import functoolsresult = (lambda k: functools.reduce (int.__mul__, range (1) (3) print (result)

#-> 6

Tip 22 find the values that appear most frequently in the list. Test = [1 print (set (test), key=test.count)) #-> 4 skill 23 resets the recursive limit.

Python limits the recursion limit to 1000. We can reset its value.

Import sysx=1001print (sys.getrecursionlimit ()) sys.setrecursionlimit (x) print (sys.getrecursionlimit ()) # 1-> 1000002-> 1001

Please apply the above techniques only when needed.

Tip 24 check the memory usage of the object.

32-bit integers consume 24 bytes in Python 2.7, while 28 bytes are used in Python 3.5. To verify memory usage, we can call the method.

Python 2.7.import sysx=1print (sys.getsizeof (x)) #-> 24Python 3.5.import sysx=1print (sys.getsizeof (x)) #-> 28 Tip 25 use _ _ slots__ to reduce memory overhead.

Have you ever observed that your Python application consumes a lot of resources, especially memory? This is a technique for using class variables to reduce memory overhead to some extent.

Import sysclass FileSystem (object): def _ init__ (self, files, folders, devices): self.files = files self.folders = folders self.devices = devicesprint (sys.getsizeof (FileSystem)) class FileSystem1 (object): _ _ slots__ = ['files',' folders', 'devices'] def _ init__ (self, files, folders Devices): self.files = files self.folders = folders self.devices = devicesprint (sys.getsizeof (FileSystem1)) # In Python 3.5-> 1016-> 888

Obviously, you can see some savings in memory usage from the results. But when the memory overhead of a class is unnecessarily large, you should use _ _ slots__. Do this only after analyzing the application. Otherwise, you will make the code difficult to change and have no real benefits.

Tip 26 Lambda imitates the printing function. Import syslprint=lambda * args:sys.stdout.write (".join (map (str,args) lprint (" python "," tips ", 1000 Magi 1001) #-> python tips 1000 1001 Tip 27 create dictionaries from two related sequences. T1 = (1,2,3) T2 = (10,20,30) print (dict (zip (T1 ~ T2) #-> {1: 10,2: 20,3: 30} Tip 28 searches for multiple prefixes in the string online. Print ("http://www.baidu.com".startswith(("http://"," https://")))print("https://juejin.cn".endswith((".com", ".cn")) # 1-> True#2- > True Tip 29 forms a unified list without using any loops. Import itertoolstest = [[- 1,-2], [30, 40], [25, 35] print (list (itertools.chain.from_iterable (test) #-> [- 1,-2, 30, 40, 25, 35]

If you have an input list that contains nested lists or tuples as elements, use the following techniques. The limitation here, however, is that it uses for loops.

Def unifylist (l_input, l_target): for it in l_input: if isinstance (it, list): unifylist (it, l_target) elif isinstance (it, tuple): unifylist (list (it), l_target) else: l_target.append (it) return l_targettest = [- 1,-2], [1, 2], [4, (5) ]], (30,40), [25,35]] print (unifylist (test, [])) # Output = > [- 1,-2, 1, 2, 3, 4, 5, 6 jurisdiction 7, 30, 40, 25, 35]

An easier way to unify lists that contain lists and tuples is to use the Python

< more_itertools >

Bag. It doesn't need a loop. Just execute

< pip install more_itertools >

If not already.

Import more_itertoolstest = [[- 1,-2], [1, 2, 3, [4, (5, [6, 7])], (30, 40), [25, 35]] print (list (more_itertools.collapse (test) # Output= > [- 1,-2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35] Tips 30 implement real switch-case statements in Python.

This is code that uses dictionaries to mimic switch-case construction.

Def xswitch (x): return xswitch._system_dict.get (x, None) xswitch._system_dict = {'files': 10,' folders': 5, 'devices': 2} print (xswitch (' default')) print (xswitch ('devices')) # 1-> None#2- > 2 "how Python uses ternary operators for conditional assignments" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report