In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you what skills to use Python, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
1. How to determine whether all the values in a list are less than a certain number # 1. Determine whether all the values in a list are less than a certain number num = 10list1 = [1, 1, 5, 5, 7, 1] # bronze player index = 0for n in list1: if n
< num : index += 1 continue else: print("青铜选手", False) breakif index == len(list1): print("青铜选手", True)# 王者选手print("王者选手", all(map(lambda x: x < num, list1)))Bronze contestant: the most intuitive way is to traverse one by one to determine whether the elements in the list are less than a certain value, it is too simple.
Masters: using two Python built-in functions + Python anonymous functions, one line of code can be easily solved. So easy~
two。 How to sort the strings in the list according to specific requirements # 2. Sort the strings in the list according to specific requirements list2 = ["low", "irving", "james", "durant"] def first_c (str1): return ord (str1 [0]) # Bronze player Bubble sort for i in range (len (list2)): for j in range (len (list2)-I-1): if len (List2 [j]) > len (List2j + 1): list2 [j] List2 [juni1] = list2 [juni1], list2 [j] print ("Bronze contestant:", list2) # Masters print ("Masters:", sorted (list2, key=len)) print ("by acronym:", sorted (list2, key=first_c))
Bronze player: the string sorting algorithm in the list can be done, such as the most classic bubble sorting, how about?
Masters: use the built-in function sorted one line of code to solve. Not only that, for the keyword-specified aspect of sorting, I can also set the sorting function myself, such as the firstC function above, which sorts by the first letter of the string. Do you envy it?
3. How to sort dictionaries by key or value # 3. Sort dictionaries by key or numeric value dict3 = {"low": 3, "irving": 6, "james": 1, "durant": 4} # Bronze contestant list3 = sorted (dict3.items (), key=lambda x: X [0]) dict3_keys = {iRV j for I, j in list3} print ("Bronze key sort:", dict3_keys) list3 = sorted (dict3.items (), key=lambda x: X [1]) dict3_values = {iRJ for I J in list3} print ("Bronze player by value:", dict3_values) # King player dict3_keys = {key: dict3 [key] for key in sorted (dict3)} print ("King player key order:", dict3_keys) dict3_values = {key: dict3 [key] for key in sorted (dict3, key=dict3.get)} print ("King player by value:", dict3_values)
Bronze player: this time I used the sorted built-in function to sort it, and then converted it to dictionary form. Two lines of code are done!
King player: bronze player your method will result in a waste of space resources in the process of conversion. I directly use the sorting of keys or values, and then use the sorted keys or values to construct the final dictionary, and the program is simple.
4. How to convert the number in the list into the string # 4. Convert the numbers in the list into the string list4 = [1, 3, 5, 7, 12, 6] # Bronze player directly converts list_str4 = [str (I) for i in list4] print ("Bronze player:", list_str4) # the king player uses the map function list_str4 = list (map (str, list4)) print ("Masters:", list_str4)
Bronze player: I use a list parsing scheme to generate new lists by iterating through a loop. It's simple enough this time, and it doesn't waste space.
Masters: I used the map built-in function to convert the numbers in the list into strings. Let's call it even this time.
5. How to determine whether the elements in the list belong to the same type # 5. Determine whether the elements in the list belong to the same type list5 = ['1bronze,' 3bronze, '5bronze,' 7bronze, '12bronze,' 6'] # Bronze contestants judge each element index = 0for element in list5: if not isinstance (element, str): print ("Bronze player:", False) break index + = 1if index = len (list5): print ("Bronze player:" True) # Masters def checkStr (x): if isinstance (x, str): return True else: return Falseprint ("Masters:", all (list (map (checkStr, list5)
Bronze player: the method I use this time is to judge each element in the list one by one, and if any element is not a string, output False. At the end of the full loop, if the index value is equal to the total length of the list, True is output.
Masters: use the map function to determine whether each element in the list satisfies the function checkStr. Use the all function to get the final result. Isn't it easier?
6. How to reverse the list # 6. Reverse the list list6 = [1, 3, 5, 7, 12, 6] # Bronze contestant new_list6 = [] for i in range (len (list6)-1,-1,-1): new_list6.append (List6 [I]) print ("Bronze player:", new_list6) # King player print ("King contestant:" List6 [:-1]) list6.reverse () print ("Masters:" list6)
Bronze contestant: create a new list object and add elements from list6 to the new list in a back-to-forward manner.
Masters: I have two ways. The first way is to use the list slicing method to get the reversed list. The second way is to use the reverse function of the list, but the reverse function can only be modified in the original list, not create a new list. Yeah~~
7. How to randomly select an element # 7 from an iterable object. Randomly select an element import randomrandom.seed (0) list7 = ['613,' 1200, '74th,' 54th, '34th,' 1'] tuple7 = ("low", "irving", "james", "durant") print (random.choice (list7)) print (random.choices (tuple7, KFL3)) print (random.sample (list7, KF2)) from an iterable object
Bronze player: I won't. I can only hand in the blank paper.
Masters: Xiaoqing, move your stools and listen carefully! To select random values in Python, you can use Python's built-in library random. In the above function, choice function randomly selects a value from the list, choices function returns k values, and sample selects k values without putting back. There are three poses in total. Have you learned it?
8. How to use lists to create dictionaries
# 8. Create the dictionary list8_1 = ["low", "irving", "james", "durant"] list8_2 = [3,6,7,2] list8_3 = [5,8,1,3] # Bronze player dict8 = {} for i in range (len (list8_1)): list8_2 [I] print ("Bronze player:", dict8) # King dict8 = dict (list8_1 (list8_1) List8_2) dict8_2 = dict (zip (list8_1, zip (list8_2, list8_3)) print ("Masters:", dict8) print ("Masters:", dict8_2)
Bronze player: create a dictionary with a list, and then use the for loop to create an item of key-value pairs in the dictionary. This time I will!
Masters: use the zip built-in function to create a zip object, and use the dict function to convert the zip object into a dictionary, one line of code is done. A complete victory!
9. Filter out the string # 9 that begins with a vowel. Select the string list9 = ["low", "irving", "james", "durant", "allen"] # Bronze contestant new_list9 = [] for name in list9: if name [0] .lower () in "aeiou": new_list9.append (name) print ("Bronze player:", new_list9) print ("Masters:", list (lambda x: x.lower (). Startswith (('a')) ) print ("Masters:", [name for name in list9 if name [0] in 'aeiouAEIOU'])
Bronze player: each string element in list9 is judged, and if the first letter of the string is the reason letter, the string is added to the new list new_list9.
Masters: directly use list parsing or filter function to filter elements in list9 that satisfy anonymous functions. Compared with map function, filter function can directly filter out the element values that meet the conditions. Isn't it easier?
10. Method of creating a counting dictionary # 10. Create a counting dictionary from collections import Counterlist10 = ["low", "irving", "james", "durant", "allen", "irving", "james", "allen", "durant", "durant"] # Bronze player dict10 = {name:0 for name in set (list10)} for name in list10: if name in dict10: dict10 [name] + = 1 else: dict10 [name] = 1print ("Bronze player:" Dict10) # Masters print ("Masters:", dict (Counter (list10)
Bronze player: first create a dictionary whose keys contain all the elements that have appeared in list10, and then count the number of occurrences of the elements in the list one by one. Isn't that all right?
Masters: use the Counter class in the collections library to directly count the number of elements in list10, and then use the dict function to convert Counter objects into dictionary objects.
The above is all the contents of this article entitled "what are the skills of using 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.
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.