喝杯咖啡的功夫就能学会的100个非常有用的Python技巧(3)

2024-06-21 08:08

本文主要是介绍喝杯咖啡的功夫就能学会的100个非常有用的Python技巧(3),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

点击上方“AI公园”,关注公众号,选择加“星标“或“置顶”

因公众号更改了推送规则,记得读完点“在看”~下次AI公园的新文章就能及时出现在您的订阅列表中


作者:Fatos Morina

编译:ronghuaiyang

导读

接上一篇,67~100条。

67. 根据参数从右侧移除字符

string = "This is a sentence with "
# Remove trailing spaces from the right
print(string.rstrip())  # "This is a sentence with"
string = "this here is a sentence…..,,,,aaaaasd"
print(string.rstrip(“.,dsa”))  # "this here is a sentence"

类似地,你可以根据参数从左边删除字符:

string = "ffffffffFirst"
print(string.lstrip(“f”))  # First

68. 检查一个字符串是否代表一个数字

string = "seven"
print(string.isdigit())  # Falsestring = "1337"
print(string.isdigit())  # Truestring = "5a"
print(string.isdigit())  # False, because it contains the character 'a'string = "2**5"
print(string.isdigit())  # False

69. 检查一个字符串是否代表一个中文数字

# 42673 in Arabic numerals
string = "四二六七三"print(string.isdigit())  # False
print(string.isnumeric())  # True

70. 检查一个字符串是否所有的单词都以大写字母开头

string = "This is a sentence"
print(string.istitle())  # Falsestring = "10 Python Tips"
print(string.istitle())  # Truestring = "How to Print A String in Python"
# False, because of the first characters being lowercase in "to" and "in"
print(string.istitle())string = "PYTHON"
print(string.istitle())  # False. It's titlelized version is "Python"

71. 我们也可以在元组中使用负索引

numbers = (1, 2, 3, 4)print(numbers[-1])  # 4
print(numbers[-4])  # 1

72. 在元组中嵌套列表和元组

mixed_tuple = (("a"*10, 3, 4), ['first', 'second', 'third'])print(mixed_tuple[1])  # ['first', 'second', 'third']
print(mixed_tuple[0])  # ('aaaaaaaaaa', 3, 4)

73. 快速计算满足条件的元素在列表中出现的次数

names = ["Besim", "Albert", "Besim", "Fisnik", "Meriton"]print(names.count("Besim"))  # 2

74. 使用slice()可以方便的得到最近的元素

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slicing = slice(-4, None)# Getting the last 3 elements from the list
print(my_list[slicing])  # [4, 5, 6]# Getting only the third element starting from the right
print(my_list[-3])  # 4

你也可以使用*slice()*来完成其他常见的切片任务,比如:

string = "Data Science"# start = 1, stop = None (don't stop anywhere), step = 1
# contains 1, 3 and 5 indices
slice_object = slice(5, None)print(string[slice_object])   # Science

75. 计算元素在元组中出现的次数

my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.count('a'))  # 3

76. 获取元组中元素的索引

my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.index('f'))  #  2

77. 通过跳转获取子元组

my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[::3])  # (1, 4, 7, 10)

78. 从索引开始获取子元组

my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[3:])  # (4, 5, 6, 7, 8, 9, 10)

79. 从列表、集合或字典中删除所有元素

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)  # {}

80. 合并2个集合

一种方法是使用方法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}

81. 打印函数内的条件语句

def is_positive(number):print("Positive" if number > 0 else "Negative")  # Positiveis_positive(-3)

82. 一个if语句中包含多个条件

math_points = 51
biology_points = 78
physics_points = 56
history_points = 72my_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.")
# Congratulations! You have passed all of the exams.

83. 在一个if语句中至少满足一个条件

math_points = 51
biology_points = 78
physics_points = 56
history_points = 72my_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.")
# Congratulations! You have passed all of the exams.

84. 任何非空字符串都被计算为True

print(bool("Non empty"))  # True
print(bool(""))  # False

85. 任何非空列表、元组或字典都被求值为True

print(bool([]))  # False
print(bool(set([])))  # Falseprint(bool({}))  # False
print(bool({"a": 1}))  # True

86. 其他计算为False的值是None、“False”和数字0

print(bool(False))  # False
print(bool(None))  # False
print(bool(0))  # False

87. 你不能仅仅通过在函数中提及全局变量来改变它的值

string = "string"def do_nothing():string = "inside a method"do_nothing()print(string)  # string

你也需要使用访问修饰符global:

string = "string"def do_nothing():global stringstring = "inside a method"do_nothing()print(string)  # inside a method

88. 使用“collections”中的Counter计算字符串或列表中的元素数量

from collections import Counterresult = 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})

89. 使用Counter检查是否2个字符串包含相同的字符

from collections import Counterdef 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'))  # True
print(check_if_anagram('Here', 'Rehe'))  # True
print(check_if_anagram('Know', 'Now'))  # False

你也可以使用*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"))  # True
print(check_if_anagram("Here", "Rehe"))  # True
print(check_if_anagram("Know", "Now"))  # False

90. 使用" itertools "中的" Count "计算元素的数量

from itertools import countmy_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

91. 根据字符串或列表的频率对元素进行排序

来自collections模块的Counter默认情况下不会根据元素的频率来排序。

from collections import Counterresult = 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)]

92. 在一行中找到列表中出现频次最高的元素

my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']print(max(set(my_list), key=my_list.count))  # a

93. copy()和deepcopy()的区别

来自文档中的解释:

浅拷贝构造一个新的复合对象,然后(在可能的范围内)在其中插入对原始对象的引用。深拷贝构造一个新的复合对象,然后递归地将在原始对象中找到的对象的副本插入其中。

更全面的描述:

浅拷贝意味着构造一个新的集合对象,然后用对原始集合中的子对象的引用填充它。从本质上说,浅拷贝的深度只有一层。拷贝过程不会递归,因此不会创建子对象本身的副本。深拷贝使拷贝过程递归。这意味着首先构造一个新的集合对象,然后用在原始集合对象中找到的子对象的副本递归地填充它。以这种方式拷贝对象将遍历整个对象树,以创建原始对象及其所有子对象的完全独立的克隆。

这里是copy()的例子:

first_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = first_list.copy()first_list[0][2] = 831print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list)  # [[1, 2, 831], ['a', 'b', 'c']]

这个是deepcopy() 的例子:

import copyfirst_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = copy.deepcopy(first_list)first_list[0][2] = 831print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list)  # [[1, 2, 3], ['a', 'b', 'c']]

94. 当试图访问字典中不存在的键时,可以避免抛出错误

如果你使用一个普通的字典,并试图访问一个不存在的键,那么你将得到一个错误:

my_dictonary = {"name": "Name", "surname": "Surname"}print(my_dictonary["age"])  

下面是抛出的错误:

KeyError: 'age'

我们可以使用defaultdict():来避免这种错误

from collections import defaultdictmy_dictonary = defaultdict(str)
my_dictonary['name'] = "Name"
my_dictonary['surname'] = "Surname"print(my_dictonary["age"])  

95. 你可以构建自己的迭代器

class OddNumbers:def __iter__(self):self.a = 1return selfdef __next__(self):x = self.aself.a += 2return xodd_numbers_object = OddNumbers()
iterator = iter(odd_numbers_object)print(next(iterator))  # 1
print(next(iterator))  # 3
print(next(iterator))  # 5

96. 可以用一行从列表中删除重复项

my_set = set([1, 2, 1, 2, 3, 4, 5])
print(list(my_set))  # [1, 2, 3, 4, 5]

97. 打印模块所在的位置

import torchprint(torch)  # <module 'torch' from '/Users/...'

98. 可以使用" not in "来检查值是否不属于列表

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)  # [0, 2, 4, 6, 8]

99. sort() 和 sorted()的差别

sort()对原始列表进行排序。

sorted()返回一个新的排序列表。

groceries = ['milk', 'bread', 'tea']new_groceries = sorted(groceries)
# new_groceries = ['bread', 'milk', 'tea']print(new_groceries)# groceries = ['milk', 'bread', 'tea']
print(groceries)groceries.sort()# groceries = ['bread', 'milk', 'tea']
print(groceries)

100. 使用uuid模块生成唯一的id

UUID代表统一唯一标识符。

import uuid# Generate a UUID from a host ID, sequence number, and the current time
print(uuid.uuid1())  # 308490b6-afe4-11eb-95f7-0c4de9a0c5af# Generate a random UUID
print(uuid.uuid4())  # 93bc700b-253e-4081-a358-24b60591076a

—END—

英文原文:https://towardsdatascience.com/100-helpful-python-tips-you-can-learn-before-finishing-your-morning-coffee-eb9c39e68958

请长按或扫描二维码关注本公众号

喜欢的话,请给我个在看吧

这篇关于喝杯咖啡的功夫就能学会的100个非常有用的Python技巧(3)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1080666

相关文章

【EverEdit】活用 EverEdit 小技巧

【EverEdit】活用 EverEdit 小技巧 (1)设置 EverEdit 对比文件文本内容 设置如下图所示: 首先要先打开要对比的文本文件,和对比文件相比,此时打开了至少两个文件: 选择文件比较: (2)如何设置 EverEdit 监视文件的变化 设置如下图所示:

Python 字符串占位

在Python中,可以使用字符串的格式化方法来实现字符串的占位。常见的方法有百分号操作符 % 以及 str.format() 方法 百分号操作符 % name = "张三"age = 20message = "我叫%s,今年%d岁。" % (name, age)print(message) # 我叫张三,今年20岁。 str.format() 方法 name = "张三"age

一道经典Python程序样例带你飞速掌握Python的字典和列表

Python中的列表(list)和字典(dict)是两种常用的数据结构,它们在数据组织和存储方面有很大的不同。 列表(List) 列表是Python中的一种有序集合,可以随时添加和删除其中的元素。列表中的元素可以是任何数据类型,包括数字、字符串、其他列表等。列表使用方括号[]表示,元素之间用逗号,分隔。 定义和使用 # 定义一个列表 fruits = ['apple', 'banana

Python应用开发——30天学习Streamlit Python包进行APP的构建(9)

st.area_chart 显示区域图。 这是围绕 st.altair_chart 的语法糖。主要区别在于该命令使用数据自身的列和指数来计算图表的 Altair 规格。因此,在许多 "只需绘制此图 "的情况下,该命令更易于使用,但可定制性较差。 如果 st.area_chart 无法正确猜测数据规格,请尝试使用 st.altair_chart 指定所需的图表。 Function signa

python实现最简单循环神经网络(RNNs)

Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以向量的形式进行表示。 绿色部分是隐藏向量。是加工处理过程。 蓝色部分是输出向量。 python代码表示如下: rnn = RNN()y = rnn.step(x) # x为输入向量,y为输出向量 RNNs神经网络由神经元组成, python

python 喷泉码

因为要完成毕业设计,毕业设计做的是数据分发与传输的东西。在网络中数据容易丢失,所以我用fountain code做所发送数据包的数据恢复。fountain code属于有限域编码的一部分,有很广泛的应用。 我们日常生活中使用的二维码,就用到foutain code做数据恢复。你遮住二维码的四分之一,用手机的相机也照样能识别。你遮住的四分之一就相当于丢失的数据包。 为了实现并理解foutain

python 点滴学

1 python 里面tuple是无法改变的 tuple = (1,),计算tuple里面只有一个元素,也要加上逗号 2  1 毕业论文改 2 leetcode第一题做出来

邮件群发推送的方法技巧?有哪些注意事项?

邮件群发推送的策略如何实现?邮件推送怎么评估效果? 电子邮件营销是现代企业进行推广和沟通的重要工具。有效的邮件群发推送不仅能提高客户参与度,还能促进销售增长。AokSend将探讨一些关键的邮件群发推送方法和技巧,以帮助企业优化其邮件营销策略。 邮件群发推送:目标受众 了解他们的需求、兴趣和行为习惯有助于你设计出更具吸引力和相关性的邮件内容。通过收集和分析数据,创建详细的客户画像,可以更精

Python爬虫-贝壳新房

前言 本文是该专栏的第32篇,后面会持续分享python爬虫干货知识,记得关注。 本文以某房网为例,如下图所示,采集对应城市的新房房源数据。具体实现思路和详细逻辑,笔者将在正文结合完整代码进行详细介绍。接下来,跟着笔者直接往下看正文详细内容。(附带完整代码) 正文 地址:aHR0cHM6Ly93aC5mYW5nLmtlLmNvbS9sb3VwYW4v 目标:采集对应城市的

python 在pycharm下能导入外面的模块,到terminal下就不能导入

项目结构如下,在ic2ctw.py 中导入util,在pycharm下不报错,但是到terminal下运行报错  File "deal_data/ic2ctw.py", line 3, in <module>     import util 解决方案: 暂时方案:在终端下:export PYTHONPATH=/Users/fujingling/PycharmProjects/PSENe