社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

机器学习研究组订阅 • 4 年前 • 470 次点击  

作者:Fatos Morina

编译:ronghuaiyang

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())  # False

string = "10 Python Tips"
print(string.istitle())  # True

string = "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 = (1234)

print(numbers[-1])  # 4
print(numbers[-4])  # 1

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

mixed_tuple = (("a"*1034), ['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 = [12345678910]
slicing = slice(-4None)

# 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(5None)

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 = (12345678910)

print(my_tuple[::3])  # (1, 4, 7, 10)

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

my_tuple = (12345678910)

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

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

my_list = [1234]
my_list.clear()
print(my_list)  # []

my_set = {123}
my_set.clear()
print(my_set)  # set()

my_dict = {"a"1"b"2}
my_dict.clear()
print(my_dict)  # {}

80. 合并2个集合

一种方法是使用方法union(),它将作为合并的结果返回一个新的集合:

first_set = {456}
second_set = {123}

print(first_set.union(second_set))  # {1, 2, 3, 4, 5, 6}

另一个是方法update,它将第二个集合的元素插入到第一个集合中:

first_set = {456}
second_set = {123}

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")  # Positive

is_positive(-3)

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

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.")
# Congratulations! You have passed all of the exams.

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

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 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([])))  # False

print(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 string
    string = "inside a method"

do_nothing()

print(string)  # inside a method

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

from collections import Counter

result = Counter("Banana")
print(result)  # Counter({'a': 3, 'n': 2, 'B': 1})

result = Counter([1213141516])
print(result)  # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

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

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'))  # 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 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

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

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

from collections import Counter

result = Counter([1232222])
print(result)  # Counter({2: 5, 1: 1, 3: 1})
print(result.most_common())  # [(2, 5), (1, 1), (3, 1)]

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

my_list = ['1'10

'a''b'2'a''c''a']

print(max(set(my_list), key=my_list.count))  # a

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

来自文档中的解释:

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

更全面的描述:

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

这里是copy()的例子:

first_list = [[123], ['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 = [[123], ['a' 'b''c']]

second_list = copy.deepcopy(first_list)

first_list[0][2] = 831

print(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 defaultdict

my_dictonary = defaultdict(str)
my_dictonary['name'] = "Name"
my_dictonary['surname'] = "Surname"

print(my_dictonary["age"])  

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

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))  # 1
print(next(iterator))  # 3
print(next(iterator))  # 5

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

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

97. 打印模块所在的位置

import torch

print(torch)  

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

odd_numbers = [13579]
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


想要了解更多资讯,请扫描下方二维码,关注机器学习研究会

                                          


转自:AI公园

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/114439
 
470 次点击