本文最后更新于 689 天前,其中的信息可能已经有所发展或是发生改变。
目前Python可以说是非常流行,在目前的编程语言中,Python的抽象程度是最高的,是最接近自然语言的,很容易上手。你可以用它来完成很多任务,比如数据科学、机器学习、Web开发、脚本编写、自动化等。
下面,羽峰继续给大家分享100个Python小技巧中剩余的50个,帮助大家更好地了解和学习Python。
map()函数将给定函数应用于可迭代对象(列表、元组等),然后返回结果(map对象)。
| my_list = [1, 2, 3, 4] |
| |
| squared = map(lambda x: x**2, my_list) |
| |
| print(list(squared)) |
| print(my_list) |
| for number in range(1, 10, 3): |
| print(number, end=" ") |
| |
| def range_with_zero(number): |
| for i in range(0, number): |
| print(i, end=' ') |
| |
| def range_with_no_zero(number): |
| for i in range(number): |
| print(i, end=' ') |
| |
| range_with_zero(3) |
| range_with_no_zero(3) |
| def check_if_anagram(first_word, second_word): |
| first_word = first_word.lower() |
| second_word = second_word.lower() |
| return sorted(first_word) == sorted(second_word) |
| |
| print(check_if_anagram("testinG", "Testing")) |
| print(check_if_anagram("Here", "Rehe")) |
| print(check_if_anagram("Know", "Now")) |
但是,只有最后一个会被调用,覆盖以前。
| def get_address(): |
| return "First address" |
| |
| def get_address(): |
| return "Second address" |
| |
| def get_address(): |
| return "Third address" |
| |
| print(get_address()) |
在定义属性或方法时,在属性名或者方法名前增加两个下划线,定义的就是私有属性或方法。
如果想要在外部访问,那么只需要在名称前面加上 '_类名' 变成 '_类名__名称'。
| class Engineer: |
| def __init__(self, name): |
| self.name = name |
| self.__starting_salary = 62000 |
| |
| dain = Engineer('Dain') |
| print(dain._Engineer__starting_salary) |
sort():对原始列表进行排序
sorted():返回一个新的排序列表
| groceries = ['milk', 'bread', 'tea'] |
| |
| new_groceries = sorted(groceries) |
| |
| |
| print(new_groceries) |
| |
| |
| print(groceries) |
| |
| groceries.sort() |
| |
| |
| print(groceries) |
| def get_sum(*arguments): |
| result = 0 |
| for i in arguments: |
| result += i |
| return result |
| |
| print(get_sum(1, 2, 3)) # 6 |
| print(get_sum(1, 2, 3, 4, 5)) # 15 |
| print(get_sum(1, 2, 3, 4, 5, 6, 7)) # 28 |
| string = "This is just a sentence." |
| result = string.swapcase() |
| |
| print(result) |
在两个int数据类型之间使用 + 运算符时,将得到它们的和。
而在两个字符串数据类型之间使用它时,会将其合并。
| print(10 + 1) |
| print('first' + 'second') |
这个就是操作符重载,你还可以在类中使用(add)。
| class Expenses: |
| def __init__(self, rent, groceries): |
| self.rent = rent |
| self.groceries = groceries |
| |
| def __add__(self, other): |
| return Expenses(self.rent + other.rent, |
| self.groceries + other.groceries) |
| |
| april_expenses = Expenses(1000, 200) |
| may_expenses = Expenses(1000, 300) |
| |
| total_expenses = april_expenses + may_expenses |
| print(total_expenses.rent) |
| print(total_expenses.groceries) |
下面定义一个操作重载示例( < 操作符),使用lt方法。
| class Game: |
| def __init__(self, score): |
| self.score = score |
| |
| def __lt__(self, other): |
| return self.score < other.score |
| |
| first = Game(1) |
| second = Game(2) |
| |
| print(first < second) |
同样的,== 操作符使用eq方法。
| class Journey: |
| def __init__(self, location, destination, duration): |
| self.location = location |
| self.destination = destination |
| self.duration = duration |
| |
| def __eq__(self, other): |
| return ((self.location == other.location) and |
| (self.destination == other.destination) and |
| (self.duration == other.duration)) |
| |
| first = Journey('Location A', 'Destination A', '30min') |
| second = Journey('Location B', 'Destination B', '30min') |
| |
| print(first == second) |
还有一些其他的定义。
| __sub__() for - |
| __mul__() for * |
| __truediv__() for / |
| __ne__() for != |
| __ge__() for >= |
| __gt__() for > |
| class Rectangle: |
| def __init__(self, a, b): |
| self.a = a |
| self.b = b |
| |
| def __repr__(self): |
| return repr('Rectangle with area=' + str(self.a * self.b)) |
| |
| print(Rectangle(3, 4)) |
使用super函数调用父类的初始化方法。
| class Parent: |
| def __init__(self, city, address): |
| self.city = city |
| self.address = address |
| |
| class Child(Parent): |
| def __init__(self, city, address, university): |
| super().__init__(city, address) |
| self.university = university |
| |
| child = Child('Peking University', 'Fudan University', 'Tsinghua University') |
| print(child.university) |
使用父类的名称调用父类。
| class Parent: |
| def __init__(self, city, address): |
| self.city = city |
| self.address = address |
| |
| class Child(Parent): |
| def __init__(self, city, address, university): |
| Parent.__init__(self, city, address) |
| self.university = university |
| |
| child = Child('Peking University', 'Fudan University', 'Tsinghua University') |
| print(child.university) |
| string = " " |
| result = string.isspace() |
| |
| print(result) |
| name = "Password" |
| print(name.isalnum()) |
| |
| name = "Secure Password " |
| print(name.isalnum()) |
| |
| name = "S3cur3P4ssw0rd" |
| print(name.isalnum()) |
| |
| name = "133" |
| print(name.isalnum()) |
| string = "Name" |
| print(string.isalpha()) |
| |
| string = "Firstname Lastname" |
| print(string.isalpha()) |
| |
| string = "P4ssw0rd" |
| print(string.isalpha()) |
从右侧开始。
| string = "This is a sentence with " |
| print(string.rstrip()) |
| |
| string = "this here is a sentence…..,,,,aaaaasd" |
| print(string.rstrip(".,dsa")) |
同样的,左侧也能操作。
| string = "ffffffffFirst" |
| print(string.lstrip("f")) |
| string = "seven" |
| print(string.isdigit()) |
| |
| string = "1337" |
| print(string.isdigit()) |
| |
| string = "5a" |
| print(string.isdigit()) |
| |
| string = "2**5" |
| print(string.isdigit()) |
| |
| string = "四二六七三" |
| |
| print(string.isdigit()) |
| print(string.isnumeric()) |
| string = "This is a sentence" |
| print(string.istitle()) |
| |
| string = "10 Python Tips" |
| print(string.istitle()) |
| |
| string = "How to Print A String in Python" |
| |
| print(string.istitle()) |
| |
| string = "PYTHON" |
| print(string.istitle()) |
| numbers = (1, 2, 3, 4) |
| |
| print(numbers[-1]) # 4 |
| print(numbers[-4]) # 1 |
| mixed_tuple = (("a"*10, 3, 4), ['first', 'second', 'third']) |
| |
| print(mixed_tuple[1]) # ['first', 'second', 'third'] |
| print(mixed_tuple[0]) # ('aaaaaaaaaa', 3, 4) |
| names = ["Besim", "Albert", "Besim", "Fisnik", "Meriton"] |
| |
| print(names.count("Besim")) |
使用slice()获取最后n个元素。
| my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| slicing = slice(-4, None) |
| print(my_list[slicing]) |
| |
| print(my_list[-3]) |
使用slice()做切片任务。
| string = "Data Science" |
| |
| slice_object = slice(5, None) |
| print(string[slice_object]) |
| my_tuple = ('a', 1, 'f', 'a', 5, 'a') |
| |
| print(my_tuple.count('a')) |
| math_points = 51 |
| biology_points = 78 |
| physics_points = 56 |
| history_points = 72 |
| |
| my_conditions = [math_points > 50, biology_points > 50, |
| physics_points > 50, history_points > 50] |
| |
| if all(my_conditions): |
| print("Congratulations! You have passed all of the exams.") |
| else: |
| print("I am sorry, but it seems that you have to repeat at least one exam.") |
| |
UUID代表唯一标识符。
| import uuid |
| |
| |
| print(uuid.uuid1()) |
| |
| |
| print(uuid.uuid4()) |
| my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
| |
| print(my_tuple[3:]) # (4, 5, 6, 7, 8, 9, 10) |
| my_list = [1, 2, 3, 4] |
| my_list.clear() |
| print(my_list) # [] |
| |
| my_set = {1, 2, 3} |
| my_set.clear() |
| print(my_set) # set() |
| |
| my_dict = {"a": 1, "b": 2} |
| my_dict.clear() |
| print(my_dict) # {} |
使用union()方法,返回一个新集合。
| first_set = {4, 5, 6} |
| second_set = {1, 2, 3} |
| |
| print(first_set.union(second_set)) # {1, 2, 3, 4, 5, 6} |
还可以使用update()方法,将第二个集合的元素插入到第一个集合中去。
| first_set = {4, 5, 6} |
| second_set = {1, 2, 3} |
| |
| first_set.update(second_set) |
| |
| print(first_set) # {1, 2, 3, 4, 5, 6} |
| def is_positive(number): |
| print("Positive" if number > 0 else "Negative") |
| |
| is_positive(-3) |
| my_tuple = ('a', 1, 'f', 'a', 5, 'a') |
| |
| print(my_tuple.index('f')) |
| math_points = 40 |
| biology_points = 78 |
| physics_points = 56 |
| history_points = 72 |
| |
| my_conditions = [math_points > 50, biology_points > 50, |
| physics_points > 50, history_points > 50] |
| |
| if any(my_conditions): |
| print("Congratulations! You have passed all of the exams.") |
| else: |
| print("I am sorry, but it seems that you have to repeat at least one exam.") |
| |
| print(bool("Non empty")) |
| print(bool("")) |
| from itertools import count |
| |
| my_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] |
| |
| current_counter = count() |
| |
| string = "This is just a sentence." |
| |
| for i in string: |
| if i in my_vowels: |
| print(f"Current vowel: {i}") |
| print(f"Number of vowels found so far: {next(current_counter)}") |
输出如下。
| Current vowel: i |
| Number of vowels found so far: 0 |
| Current vowel: i |
| Number of vowels found so far: 1 |
| Current vowel: u |
| Number of vowels found so far: 2 |
| Current vowel: a |
| Number of vowels found so far: 3 |
| Current vowel: e |
| Number of vowels found so far: 4 |
| Current vowel: e |
| Number of vowels found so far: 5 |
| Current vowel: e |
| Number of vowels found so far: 6 |
| print(bool(False)) |
| print(bool(None)) |
| print(bool(0)) |
在函数无法直接修改全局变量的值。
可通过修饰符global,修改全局变量的值。
| string = "string" |
| |
| def do_nothing(): |
| global string |
| string = "inside a method" |
| |
| do_nothing() |
| |
| print(string) |
使用collections中的Counter计算字符串或列表中元素的数量。
| from collections import Counter |
| |
| result = Counter("Banana") |
| print(result) # Counter({'a': 3, 'n': 2, 'B': 1}) |
| |
| result = Counter([1, 2, 1, 3, 1, 4, 1, 5, 1, 6]) |
| print(result) # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}) |
可以使用Counter()方法。
| from collections import Counter |
| |
| def check_if_anagram(first_string, second_string): |
| first_string = first_string.lower() |
| second_string = second_string.lower() |
| return Counter(first_string) == Counter(second_string) |
| |
| print(check_if_anagram('testinG', 'Testing')) |
| print(check_if_anagram('Here', 'Rehe')) |
| print(check_if_anagram('Know', 'Now')) |
可以使用sorted()方法。
| def check_if_anagram(first_word, second_word): |
| first_word = first_word.lower() |
| second_word = second_word.lower() |
| return sorted(first_word) == sorted(second_word) |
| |
| print(check_if_anagram("testinG", "Testing")) |
| print(check_if_anagram("Here", "Rehe")) |
| print(check_if_anagram("Know", "Now")) |
| print(bool([])) |
| print(bool(set([]))) |
| |
| print(bool({})) |
| print(bool({"a": 1})) |
collections模块的Counter(),默认情况下是不会根据元素的频率对它们进行排序的。
| from collections import Counter |
| |
| result = Counter([1, 2, 3, 2, 2, 2, 2]) |
| print(result) # Counter({2: 5, 1: 1, 3: 1}) |
| print(result.most_common()) # [(2, 5), (1, 1), (3, 1)] |
map()函数将给定函数应用于可迭代对象(列表、元组等),然后返回结果(map对象)。
| my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a'] |
| |
| print(max(set(my_list), key=my_list.count)) |
浅拷贝: 拷贝父对象,但是不会拷贝对象的内部的子对象。
深拷贝: 拷贝父对象. 以及其内部的子对象。
下面是一个copy()的例子。
| first_list = [[1, 2, 3], ['a', 'b', 'c']] |
| |
| second_list = first_list.copy() |
| |
| first_list[0][2] = 831 |
| |
| print(first_list) # [[1, 2, 831], ['a', 'b', 'c']] |
| print(second_list) # [[1, 2, 831], ['a', 'b', 'c']] |
这里是一个deepcopy()的例子。
| import copy |
| |
| first_list = [[1, 2, 3], ['a', 'b', 'c']] |
| |
| second_list = copy.deepcopy(first_list) |
| |
| first_list[0][2] = 831 |
| |
| print(first_list) |
| print(second_list) |
如果你想访问字典一个不存在的键,代码会报错。
| my_dictonary = {"name": "Name", "surname": "Surname"} |
| print(my_dictonary["age"]) |
错误如下。
可以通过使用defaultdict(),代码将不会报错。
| from collections import defaultdict |
| |
| my_dictonary = defaultdict(str) |
| my_dictonary['name'] = "Name" |
| my_dictonary['surname'] = "Surname" |
| |
| print(my_dictonary["age"]) |
| my_set = set([1, 2, 1, 2, 3, 4, 5]) |
| print(list(my_set)) |
| class OddNumbers: |
| def __iter__(self): |
| self.a = 1 |
| return self |
| |
| def __next__(self): |
| x = self.a |
| self.a += 2 |
| return x |
| |
| odd_numbers_object = OddNumbers() |
| iterator = iter(odd_numbers_object) |
| |
| print(next(iterator)) |
| print(next(iterator)) |
| print(next(iterator)) |
| import sys |
| |
| print(sys.getsizeof("bitcoin")) |
| import pandas |
| |
| print(pandas) |
| odd_numbers = [1, 3, 5, 7, 9] |
| even_numbers = [] |
| |
| for i in range(9): |
| if i not in odd_numbers: |
| even_numbers.append(i) |
| |
| print(even_numbers) |
| my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
| |
| print(my_tuple[::3]) |