用这10个小技巧加速Python编程

重磅干货,第一时间送达

>>> # Positive Indexing... numbers = [1, 2, 3, 4, 5, 6, 7, 8]... print("First Number:", numbers[0])... print("First Four Numbers:", numbers[:4])... print("Odd Numbers:", numbers[::2])...First Number: 1First Four Numbers: [1, 2, 3, 4]Odd Numbers: [1, 3, 5, 7]
>>> # Negative Indexing... data_shape = (100, 50, 4)... names = ["John", "Aaron", "Mike", "Danny"]... hello = "Hello World!"...... print(data_shape[-1])... print(names[-3:-1])... print(hello[1:-1:2])...4['Aaron', 'Mike']el ol
if len(some_list) > 0: # do something here when the list is not emptyelse: # do something else when the list is empty
>>> def check_container_empty(container):... if container:... print(f"{container} has elements.")... else:... print(f"{container} doesn't have elements.")...... check_container_empty([1, 2, 3])... check_container_empty(set())... check_container_empty({"zero": 0, "one": 1})... check_container_empty(tuple())...[1, 2, 3] has elements.set() doesn't have elements.{'zero': 0, 'one': 1} has elements.() doesn't have elements.
>>> # List of strings... # The typical way... columns = ['name', 'age', 'gender', 'address', 'account_type']... print("* Literals:", columns)...... # Do this instead... columns = 'name age gender address account_type'.split()... print("* Split with spaces:", columns)...... # If the strings contain spaces, you can use commas instead... columns = 'name, age, gender, address, account type'.split(', ')... print("* Split with commas:", columns)...* Literals: ['name', 'age', 'gender', 'address', 'account_type']* Split with spaces: ['name', 'age', 'gender', 'address', 'account_type']* Split with commas: ['name', 'age', 'gender', 'address', 'account type']
# The typical wayif score > 90: reward = "1000 dollars"else: reward = "500 dollars"# Do this insteadreward = "1000 dollars" if score > 90 else "500 dollars"
# Another possible scenario# You got a reward amount from somewhere else, but don't know if None/0 or notreward = reward_known or "500 dollars"# The above line of code is equivalent to belowreward = reward_known if reward_known else "500 dollars"
>>> # Create a text file that has the text: Hello World!...... # Open the file and append some new data... text_file0 = open("hello_world.txt", "a")... text_file0.write("Hello Python!")...... # Open the file again for something else... text_file1 = open("hello_world.txt")... print(text_file1.read())...Hello World!
>>> with open("hello_world.txt", "a") as file:... file.write("Hello Python!")...... with open("hello_world.txt") as file:... print(file.read())...... print("Is file close?", file.closed)...Hello World!Hello Python!Hello Python!Is file close? True
# Multiple Comparisons# The typical wayif a < 4 and a > 1: # do something here# Do this insteadif 1 < a < 4: # do somerthing here
# The typical wayif b == "Mon" or b == "Wed" or b == "Fri" or b == "Sun": # do something here# Do this instead, you can also specify a tuple ("Mon", "Wed", "Fri", "Sun")if b in "Mon Wed Fri Sun".split(): # do something here
# The typical waysif a < 10 and b > 5 and c == 4: # do somethingif a < 10 or b > 5 or c == 4: # do something# Do these insteadif all([a < 10, b > 5, c == 4]): # do somethingif any([a < 10, b > 5, c == 4]): # do something
# The original form:def generate_plot(data, image_name): """This function creates a scatter plot for the data""" # create the plot based on the data ... if image_name: # save the image ...# In many cases, we don't need to save the imagegenerate_plot(data, None)# The one with a default valuedef generate_plot(data, image_name=None): pass# Now, we can omit the second parametergenerate_plot(data)
>>> words = ['an', 'boy', 'girl', 'an', 'boy', 'dog', 'cat', 'Dog', 'CAT', 'an','GIRL', 'AN', 'dog', 'cat', 'cat', 'bag', 'BAG', 'BOY', 'boy', 'an']... unique_words = {x.lower() for x in set(words)}... for word in unique_words:... print(f"* Count of {word}: {words.count(word)}")...* Count of cat: 3* Count of bag: 1* Count of boy: 3* Count of dog: 2* Count of an: 5* Count of girl: 1
>>> from collections import Counter...... word_counter = Counter(x.lower() for x in words)... print("Word Counts:", word_counter)...Word Counts: Counter({'an': 5, 'boy': 4, 'cat': 4, 'dog': 3, 'girl': 2, 'bag': 2})
>>> # Find out the most common item... print("Most Frequent:", word_counter.most_common(1))Most Frequent: [('an', 5)]>>> # Find out the most common 2 items... print("Most Frequent:", word_counter.most_common(2))Most Frequent: [('an', 5), ('boy', 4)]
>>> # A list of numbers and strings... numbers = [1, 3, 7, 2, 5, 4]... words = ['yay', 'bill', 'zen', 'del']... # Sort them... print(sorted(numbers))... print(sorted(words))...[1, 2, 3, 4, 5, 7]['bill', 'del', 'yay', 'zen']>>> # Sort them in descending order... print(sorted(numbers, reverse=True))... print(sorted(words, reverse=True))...[7, 5, 4, 3, 2, 1]['zen', 'yay', 'del', 'bill']
>>> # Create a list of tuples... grades = [('John', 95), ('Aaron', 99), ('Zack', 97), ('Don', 92), ('Jennifer', 100), ('Abby', 94), ('Zoe', 99), ('Dee', 93)]>>> # Sort by the grades, descending... sorted(grades, key=lambda x: x[1], reverse=True)[('Jennifer', 100), ('Aaron', 99), ('Zoe', 99), ('Zack', 97), ('John', 95), ('Abby', 94), ('Dee', 93), ('Don', 92)]>>> # Sort by the name's initial letter, ascending... sorted(grades, key=lambda x: x[0][0])[('Aaron', 99), ('Abby', 94), ('Don', 92), ('Dee', 93), ('John', 95), ('Jennifer', 100), ('Zack', 97), ('Zoe', 99)]
>>> # Requirement: sort by name initial ascending, and by grades, descending... # Both won't work... sorted(grades, key=lambda x: (x[0][0], x[1]), reverse=True)[('Zoe', 99), ('Zack', 97), ('Jennifer', 100), ('John', 95), ('Dee', 93), ('Don', 92), ('Aaron', 99), ('Abby', 94)]>>> sorted(grades, key=lambda x: (x[0][0], x[1]), reverse=False)[('Abby', 94), ('Aaron', 99), ('Don', 92), ('Dee', 93), ('John', 95), ('Jennifer', 100), ('Zack', 97), ('Zoe', 99)]>>> # This will do the trick... sorted(grades, key=lambda x: (x[0][0], -x[1]))[('Aaron', 99), ('Abby', 94), ('Dee', 93), ('Don', 92), ('Jennifer', 100), ('John', 95), ('Zoe', 99), ('Zack', 97)]
>>> student = {'name': "John", 'age': 18}... student['gender']...Traceback (most recent call last): File "<input>", line 2, in <module>KeyError: 'gender'
>>> letters = ["a", "a", "c", "d", "d", "c", "a", "b"]... final_dict = {}... for letter in letters:... if letter not in final_dict:... final_dict[letter] = []... final_dict[letter].append(letter)...... print("Final Dict:", final_dict)...Final Dict: {'a': ['a', 'a', 'a'], 'c': ['c', 'c'], 'd': ['d', 'd'], 'b': ['b']}
>>> from collections import defaultdict...... final_defaultdict = defaultdict(list)... for letter in letters:... final_defaultdict[letter].append(letter)...... print("Final Default Dict:", final_defaultdict)...Final Default Dict: defaultdict(<class 'list'>, {'a': ['a', 'a', 'a'], 'c': ['c', 'c'], 'd': ['d', 'd'], 'b': ['b']})

如果本文对小伙伴有帮助,希望可以在文末来个“一键三连”。

交流群

(0)

相关推荐