In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the "what are the tips to improve the level of Python coding" related knowledge, in the actual case of the operation process, many people will encounter such a dilemma, then 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!
1. Segmented sequence
Common sequence types are lists, tuples, and strings. By splitting another sequence, you can create a new sequence. The following features use lists as examples, but they can also be used for other sequence types such as tuples, strings, and bytes.
> > a = [0,2,4,6,8 Using a range 10,12,14,16,18,20] > # Using a range, [start, end) > > a [1:3] [2,4] > > # Using a range with a step > a [1:9:2] [2,6,10,14] > > # Leave out the start = an implicit start of 0 > > a [: 5] [0,2,4,6,8] > > # Leave out the stop = an implict end to the very last item > a [9:] [18 20] > > # Entire list > a [:] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
two。 Use reverse indexing to access elements in a sequence
Reverse counting is much easier if you want to access some elements at the end of the sequence. In the Python sequence, the index of the last element is-1, the index of the penultimate element is-2, and so on.
> a = 'Hello Worldwide' > # instead of using a [len (a)-1] > a [- 1]'! > > # in combination with slicing > a [- 5 len] 'orld'
3. Multiple assignment
Multiple assignments can be used when assigning values to several variables. With the same idiom, you can exchange two variables or two elements in the same list. This feature is closely related to the tuple unpacking that will be introduced later.
> > # instead of doing a = 8; b = 5 > a, b = 8,5 > print (fancia is {a}; b is {b}') an is 8; b is 5 > > # Swap two variables > a, bb = b, a > print (franka is {a}; b is {b}') an is 5 B is 8 > # Swap the first and last elements in a list > numbers = [1,2,3,4,5] > > numbers [0], numbers [- 1] = numbers [- 1], numbers [0] > numbers [5,2,3,4,1]
4. Reverse sequence
Sometimes you need to reverse the sequence. Although you can do this with for loop statements, there is a simpler and more straightforward approach. Similar to the above, when a feature is available for a sequence, it usually means that strings, tuples, and lists all support this feature.
> a = (1,2,3,4,5) > > a [::-1] (5,4,3,2,1) > b = 'start' > b [::-1]' trats'
5. Check whether the sequence is empty
Lists, tuples, and so on work only if the sequence is not empty, so you need to check whether the sequence is empty before the operation.
> empty_list = [(),'', [], {}, set ()] > for item in empty_list:. If not item:... Print (f'Do something with the {type (item)}'). Do something with the
To do this, you can use the not keyword to negate a sequence (for example, not []), whose value is True as long as the sequence is not empty. In addition, you can do the same for two other common data types, dict and set.
6. Set derivation
The usage of the set derivation is similar to that of the list analysis above. The difference is that the set derivation uses curly braces instead of square brackets. And, by defining the set data type, you can delete duplicate elements.
7. Dictionary generation
In addition to list parsing and set derivation, analytical features can also be used to create dictionary data types. Dict consists of key-value pairs, so the dictionary generator contains the specified key and value, separated by colons.
> a = [1, 2, 3, 4, 5] > {x: Xerox for x in a} {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
8. Generator expression
Generators in Python are an easy way to create iterators. Because the generator is "lazy" (that is, the required items can be generated only when the request is made). The generator saves a lot of memory.
A special way to create a generator is called a generator expression. With the exception of using parentheses instead of square brackets, generator expressions are syntactically similar to list parsers.
In the following example, parentheses are optional when the generator is directly used for iterating functions.
> sum (Xerox for x inrange (100)) 328350 > max ((Xerox for x inrange (100)) 9801
9. List analytic expression
A useful feature in Python is list parsing. Through the list parser, you can easily construct a list. The general format of a list parser is [some_expression for element initerable if some_condition].
> a = [1,2,3,4,5] > > [xylene 2 for x in a] [2, 4, 6, 8, 10] > [xylene 3 for x in an if x% 2 = = 1] [3, 9, 15]
10. Unpack tuple
Tuples are very common data structures in Python. They are sets of related values. Common uses of tuples include accessing their own elements. Although these elements can be accessed using an index, unpacking is an easier way.
Related to the use of unpacking, you can use underscores to represent unwanted elements and asterisks to assign values to elements other than named elements.
> items = (0, 'baud, 10, 11,' zero') > > a, b, c, d, e, f = items > print (f) zero > a, * b, c = items > print (b) ['baud dagger, 10, 11] > * _, a, b = items > print (a) 11
11. Using the Reversed () function in a for loop statement
The reversed () function, which is commonly used in for loop statements, is a way to create iterators in the reverse order of the original iterable object.
> tasks = ['laundry','picking up kids',' gardening', 'cooking'] > for task in reversed (tasks):. Print (task)... Cooking gardening picking up kids laundry
12. Zip () compression function
The zip () function is useful for one-to-one matching to join multiple iterators. If some iterators exceed the shortest iterator, they will be truncated. The zip () function returns an iterator, so it is often used in iterations. You can also use the zip () function to decompress the asterisked iterator and assign uncompressed items to variables.
> students = ('John','Mary',' Mike') > ages = (15,17,16) > scores = (90,88,82,17,14) > for student, age, score in zip (students, ages, scores): Print (f'{student}, age: {age}, score: {score}'). John, age: 15, score: 90 Mary, age: 17, score: 88 Mike, age: 16, score: 82 > > zipzipped = zip (students, ages, scores) > a, b, c = zip (* zipped) > > print (b) (15,17,16)
13. Sort with Lambdas
Lambdas expressions are anonymous functions that can receive multiple parameters with a single-line expression. A common use of lambdas is to set it to the key parameter in the built-in sorted () function.
In addition, lambdas is often used in max (), map () and other functions. Among these functions, you can replace regular functions that use the def keyword with a single-line expression.
> students = [{'name':'John',' score': 98}, {'name':' Mike',' score': 94}, {'name':'Jennifer',' score': 99}] > sorted (students, key=lambda x: X ['score']) [{' name':' Mike', 'score': 94}, {' name':'John', 'score': 98}, {' name':'Jennifer', 'score': 99}]
14. Shorthand conditional assignment
This feature is basically a grammatical sugar. When assigning a variable to a specific condition, you can use the following general shorthand assignment: y = x if condition_met elseanother_x.
> some_condition = True > # the expanded format > if some_condition:. X = 5. Else:... X = 3 > > print (fission x is {x}') x is 5 > # the shorthand way > > x = 5 if some_condition else 3 > print (flip x is {x}') x is 5
15. Use the Enumerate () enumeration function in a for loop statement
Use the enumerate () function to get iterable objects to create iterators. In addition, the enumerate () function can track the number of iterations. You can set the initial count value at will. The default initial count value is 0.
> students = ('John','Mary',' Mike') > for I, student in enumerate (students):. Print (f'Iteration: {I}, Student: {student}')... Iteration: 0, Student: John Iteration: 1, Student: Mary Iteration: 2, Student: Mike > > for I, student in enumerate (students, 35001):. Print (f'Student Name: {student}, Student ID #: {I}')... Student Name: John, Student ID #: 35001 Student Name: Mary, Student ID #: 35002 Student Name: Mike, Student ID #: 35003
16. Retrieve the value in the dictionary with the Get () method
Typically, you can specify a key in square brackets to retrieve the value of the key. However, errors can occur when the key is not in the dictionary. Of course, you can also use the try/except exception handling mechanism to solve this problem. However, when the key is not in the dictionary, you can also set the default value through the get () method.
> number_dict = {0three' KeyError, 1: 'one', 2:' two', 3: 'five'} > number_dict [5] Traceback (most recent call last): File ", line 1 in KeyError: 5 > number_dict.get (5,' five') 'five'
17. Get the key corresponding to the maximum value in the dictionary
Sometimes it is necessary to find the key corresponding to the maximum value in the dictionary. First, find the index with the largest value in the list of all values, and then find the corresponding key from another list that stores all the keys. Alternatively, an easier way is to specify the key parameter in the max () function.
For simplicity, do not consider the situation where the maximum value may be duplicated. Similarly, you can use the min () function to find the key corresponding to the minimum value.
> model_scores = {'model_a': 100,' model_z': 1988,' model_t': 150} > > # workaround > > keys, values = list (model_scores.keys ()), list (model_scores.values ()) > keys [values.index (max (values))]' model_z' > # one-line > > max (model_scores, key=model_scores.get) 'model_z'
18. Debugging with Print () function
For smaller projects, you can debug with the print () function. This function is also often used in teaching. Some tricks are often used in the print () function. The first is to end the string instead of the default newline character; the second is to use the string f-string to create a string that contains some expressions.
For i in range (5):... Print (I, end=','if I
< 4else '\n') ... 0, 1, 2, 3, 4 >For i in range (5):... Print (f'{I} & {I}', end=',' if I)
< 4 else '\n') ... 0 & 0, 1 & 1, 2 & 4, 3 & 9, 4 & 16 19. 集合元素存在性测试 有时,在对集合或匹配项进行操作之前,需要测试集合中是否存在某个元素。惯用的方法是使用关键字in。 >> > a = ('one',' two','three', 'four',' five') > if 'one' in a:. Print ('The tuple contains one.')... The tuple contains one. > b = {0: 'zero', 1:' one', 2: 'two', 3:' three'} > if 2 in b.keys ():. Print ('The dict has the key of2.')... The dict has the key of 2.
20. Walrus operator
The walrus operator (: =) is a new feature in Python version 3.8. It is just another name for the assignment expression (which assigns values to variables in the expression).
In general, when an expression uses a variable, the variable declaration must be in advance. Using the walrus operator, a variable assignment can be included in an expression and can be used immediately.
> a = ['jacks,' asides, 'kings],' c'] > > if (n: = len (a))% 2 = = 1:. Print (f'The number of letters is {n}, which is odd.')... The number of letters is 5, which is odd.
21. Split string
When working with strings, you usually separate the strings into a list of words. In this case, the delimiter of the split () function can be used, and the maximum delimiter is optional. The related functions are the rsplit () function, which is similar to the split () function, except that it is split from the right side when set up to meet the maximum segmentation requirements.
> sentence = 'this is, apython, tutorial, about, idioms.' > sentence.split (',') ['this is',' apython', 'tutorial',' about', 'idioms.'] > sentence.split (',', 2) ['this is',' apython', 'tutorial, about, idioms.'] > sentence.rsplit (',') ['this is',' apython', 'tutorial',' about' 'idioms.'] > sentence.rsplit (',', 2) ['this is, a python, tutorial',' about', 'idioms.']
twenty-two。 Map () mapping function
The map () function is a higher-order function (that is, a function that takes a function as an argument or returns a value as its output). Its general format is map (function, iterables). The map () function takes an iterable object as an argument and returns a map object, which in turn is an iterator. The number of iterating objects should match the number of parameters required by the function.
In the following example, the built-in function pow () requires two parameters. Of course, you can also use custom functions. By the way, when you use the map () function to create a list, you should be able to use list parsers to achieve the same effect.
> numbers = (1,2,4,6) > indices = (2,1,0.5,2) > > # use map () > list (map (pow, numbers, indices)) [1,2,2.0,36] > # list comprehensions > [pow (x, y) for x, y in zip (numbers, indices)] [1,2,2.0,36]
23. Filter () filter function
The filter () function filters the sequence using the specified function or lambda function. This function returns a filter object, and the filter object is an iterator. In general, the usage of this function is very similar to the map () function.
> def good_word (x: str): Has_vowels = not set ('aeiou') .isdisjoint (x.lower ())... Long_enough = len (x) > 7... Good_start = x.lower (). Startswith ('pre')... Return has_vowels & long_enough & good_start. > words = ['Good',' Presentation', 'preschool',' prefix'] > list (filter (good_word, words)) ['Presentation',' preschool']
24. Concatenate strings in iterable objects
When working with strings, it is sometimes necessary to create a single string by concatenating a series of strings within iterable objects such as lists, tuples, and so on. In this case, the join () function can be called with the desired delimiter.
> words = ('Hello','Python',' Programmers') >'! '.join (words)' Hellogged Pythony programmers'> words_dict = {0: 'zero', 1:' one', 2: 'two', 3:' three'} >'& '.join (words_dict.values ())' zero&one&two&three'
25. Find the most common elements in the list
When using a list to record something with repeating elements, such as tracking the winner of a series of games, it has to do with finding out which player has won the most times. You can use the max () function to specify the key parameter and count the elements in the collection to find the maximum value.
> winnings = ['John','Billy',' Billy', 'Sam',' Billy', 'John'] > max (set (winnings), key = winnings.count)' Billy'
twenty-six。 Verify the object type
Verifying object types is part of Python's introspection capabilities. Sometimes, before applying the corresponding function, you need to know whether the object is of a certain type. Therefore, you can use the type () function or the isinstance () function, which is more flexible and can perform one-to-many tests.
Def check_type (number):... If type (number) = = int:... Print ('do something with anint')... If isinstance (number, (int,float)): Print ('do something with anint or float')... > > check_type (5) do something with anint do something with anint or float > check_type (4.2) do something with anint or float
twenty-seven。 Any () function
Suppose you have a list of records that record the time John arrived at the workplace. If you want to know if he's been late this week, it's convenient to use the any () function. If one of the elements in the Boolean list is True, the any () function returns True.
> arrival_hours = {'Mon': 8.5,' Tue': 8.75, 'Wed': 9,' Thu': 8.5, 'Fri': 8.5} > arrival_checks = [x > 8.75 for x in arrival_hours.values ()] > any (arrival_checks) True
twenty-eight。 Track the frequency of elements in the list
If you also want to know how non-champion players perform in the game, according to the above example, you can know the situation of the second and third players. To do this, you need to find out the reward for each player. You can use dictionary generation and the sorted () function with the lambda function.
> winnings = ['John','Billy',' Billy', 'Sam',' Billy', 'John'] > tracked = {item: winnings.count (item) for item in set (winnings)} > sorted (tracked.items (), key=lambda x: X [1], reverse=True) [(' Billy', 3), ('John', 2), (' Sam', 1)]
twenty-nine。 Collective judgment function All ()
Using the above example, if you still want to know whether he arrives at work before 9:30 in a week, you can use the all () function. The all () function returns True only if all elements in the Boolean list are True.
> arrival_checks_all = [x > > all (arrival_checks) True
thirty。 Read a file with the With keyword
When working with a file, you need to open the file, process the file data, and then close the file. If the file is not closed after use, the file cannot be read after a period of time. The with keyword is very useful in this case. As shown below, the file will be closed automatically after use.
> withopen ('axifile.txt') as file:... Pass. > file.closed True, "what are the tips to improve the level of Python coding" is introduced 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.
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.