30个python使用小技巧(新手如何使用python)

网友投稿 309 2022-08-23


30个python使用小技巧(新手如何使用python)

大家好,我是小寒~

今天给大家分享30个python常用小技巧

1、列表推导

列表的元素可以在一行中进行方便的循环。

numbers = [1, 2, 3, 4, 5, 6, 7, 8] even_numbers = [number for number in numbers if number % 2 == 0] print(even_numbers)

输出:

[1,3,5,7]

同时,也可以用在字典上。

dictionary = {'first_num': 1, 'second_num': 2, 'third_num': 3, 'fourth_num': 4} oddvalues = {key: value for (key, value) in dictionary.items() if value % 2 != 0} print(oddvalues)Output: {'first_num': 1, 'third_num': 3}

2、枚举函数

枚举是一个有用的函数,用于迭代对象,如列表、字典或文件。该函数生成一个元组,其中包括通过对象迭代获得的值以及循环计数器(从0的起始位置)。当您希望根据索引编写代码时,循环计数器很方便。

sentence = 'Just do It' length = len(sentence) for index, element in enumerate(sentence): print('{}: {}'.format(index, element)) if index == 0: print('The first element!') elif index == length - 1: print('The last element!')

3、通过函数返回多个值

在设计函数时,我们经常希望返回多个值。这里我们将介绍两种典型的方法:

方法一

最简单的方式就是返回一个tuple。

get_student 函数,它根据员工的ID号以元组形式返回员工的名字和姓氏。

# returning a tuple. def get_student(id_num): if id_num == 0: return 'Taha', 'Nate' elif id_num == 1: return 'Jakub', 'Abdal' else: raise Exception('No Student with this id: {}'.format(id_num))

Student = get_student(0) print('first_name: {}, last_name: {}'.format(Student[0], Student[1]))

方法二、

返回一个字典类型。因为字典是键、值对,我们可以命名返回的值,这比元组更直观。

# returning a dictionary def get_data(id_num): if id_num == 0: return {'first_name': 'Muhammad', 'last_name': 'Taha', 'title': 'Data Scientist', 'department': 'A', 'date_joined': '20200807'} elif id_num == 1: return {'first_name': 'Ryan', 'last_name': 'Gosling', 'title': 'Data Engineer', 'department': 'B', 'date_joined': '20200809'} else: raise Exception('No employee with this id: {}'.format(id_num))

employee = get_data(0) print('first_name: {},nlast_name: {},ntitle: {},ndepartment: {},ndate_joined: {}'.format( employee['first_name'], employee['last_name'], employee['title'], employee['department'], employee['date_joined']))

4、像数学一样比较多个数字

如果你有一个值,并希望将其与其他两个值进行比较,则可以使用以下基本数学表达式:1

你也许经常使用的是这种

1

在python中,你可以这么使用

x = 5 print(1

5、将字符串转换为字符串列表:

当你输入 "[[1, 2, 3],[4, 5, 6]]" 时,你想转换为列表,你可以这么做。

import ast def string_to_list(string): return ast.literal_eval(string) string = "[[1, 2, 3],[4, 5, 6]]" my_list = string_to_list(string) print(my_list)

6、对于Else方法

Python 中 esle 特殊的用法。

number_List = [1, 3, 8, 9,1] for number in number_List: if number % 2 == 0: print(number) break else: print("No even numbers!!")

7、在列表中查找n个最大或n个最小的元素

使用 heapq 模块在列表中查找n个最大或n个最小的元素。

import heapq numbers = [80, 25, 68, 77, 95, 88, 30, 55, 40, 50] print(heapq.nlargest(5, numbers)) print(heapq.nsmallest(5, numbers))

8、在不循环的情况下重复整个字符串

value = "Taha" print(value * 5) print("-" * 21)

9、从列表中查找元素的索引

cities= ['Vienna', 'Amsterdam', 'Paris', 'Berlin'] print(cities.index('Berlin'))

10、在同一行中打印多个元素?

print("Analytics", end="") print("Vidhya") print("Analytics", end=" ") print("Vidhya") print('Data', 'science', 'blogathon', '12', sep=', ')

输出

AnalyticsVidhya Analytics Vidhya Data, science, blogathon, 12

11、把大数字分开以便于阅读

有时,当你试图打印一个大数字时,传递整数真的很混乱,而且很难阅读。然后可以使用下划线,使其易于阅读。

print(5_000_000_000_000) print(7_543_291_635)

输出:

5000000000000 7543291635

12、反转列表的切片

切片列表时,需要传递最小、最大和步长。要以相反的顺序进行切片,只需传递负步长。让我们来看一个例子:

sentence = "Data science blogathon" print(sentence[21:0:-1])

输出

nohtagolb ecneics ata

13、 “is” 和 “==” 的区别。

如果要检查两个变量是否指向同一个对象,则需要使用“is”

但是,如果要检查两个变量是否相同,则需要使用“==”。

list1 = [7, 9, 4] list2 = [7, 9, 4] print(list1 == list2) print(list1 is list2) list3 = list1 print(list3 is list1)

输出

True False True

14、在一行代码中合并两个词典。

first_dct = {"London": 1, "Paris": 2} second_dct = {"Tokyo": 3, "Seol": 4} merged = {**first_dct, **second_dct} print(merged)

输出

{‘London’: 1, ‘Paris’: 2, ‘Tokyo’: 3, ‘Seol’: 4}

15、识别字符串是否以特定字母开头

sentence = "Analytics Vidhya" print(sentence.startswith("b")) print(sentence.startswith("A"))

16、获得字符的Unicode

print(ord("T")) print(ord("A")) print(ord("h")) print(ord("a"))

17、获取字典的键值对

cities = {'London': 1, 'Paris': 2, 'Tokyo': 3, 'Seol': 4} for key, value in cities.items(): print(f"Key: {key} and Value: {value}")

18、在列表的特定位置添加值

cities = ["London", "Vienna", "Rome"] cities.append("Seoul") print("After append:", cities) cities.insert(0, "Berlin") print("After insert:", cities)

输出:

[‘London’, ‘Vienna’, ‘Rome’, ‘Seoul’] After insert: [‘Berlin’, ‘London’, ‘Vienna’, ‘Rome’, ‘Seoul’]

19、Filter() 函数

它通过在其中传递的特定函数过滤特定迭代器,并且返回一个迭代器。

mixed_number = [8, 15, 25, 30,34,67,90,5,12] filtered_value = filter(lambda x: x > 20, mixed_number) print(f"Before filter: {mixed_number}") print(f"After filter: {list(filtered_value)}")

输出:

Before filter: [8, 15, 25, 30, 34, 67, 90, 5, 12] After filter: [25, 30, 34, 67, 90]

20、创建一个没有参数个数限制的函数

def multiplication(*arguments): mul = 1 for i in arguments: mul = mul * i return mul print(multiplication(3, 4, 5)) print(multiplication(5, 8, 10, 3)) print(multiplication(8, 6, 15, 20, 5))

输出:

60 1200 72000

21、一次迭代两个或多个列表

capital = ['Vienna', 'Paris', 'Seoul',"Rome"] countries = ['Austria', 'France', 'South Korea',"Italy"] for cap, country in zip(capital, countries): print(f"{cap} is the capital of {country}")

22、检查对象使用的内存大小

import sys mul = 5*6 print(sys.getsizeof(mul))

23、 Map() 函数

map() 函数用于将特定函数应用于给定迭代器。

values_list = [8, 10, 6, 50] quotient = map(lambda x: x/2, values_list) print(f"Before division: {values_list}") print(f"After division: {list(quotient)}")

24、计算 item 在列表中出现的次数

可以在 list 上调用 count 函数。

cities= ["Amsterdam", "Berlin", "New York", "Seoul", "Tokyo", "Paris", "Paris","Vienna","Paris"] print("Paris appears", cities.count("Paris"), "times in the list")

25、在元组或列表中查找元素的索引

cities_tuple = ("Berlin", "Paris", 5, "Vienna", 10) print(cities_tuple.index("Paris")) cities_list = ['Vienna', 'Paris', 'Seoul',"Amsterdam"] print(cities_list.index("Amsterdam"))

26、2个 set 进行 join 操作

set1 = {'Vienna', 'Paris', 'Seoul'} set2 = {"Tokyo", "Rome",'Amsterdam'} print(set1.union(set2))

27、根据频率对列表的值进行排序

from collections import Counter count = Counter([7, 6, 5, 6, 8, 6, 6, 6]) print(count) print("Sort values according their frequency:", count.most_common())

输出:

Counter({6: 5, 7: 1, 5: 1, 8: 1}) Sort values according their frequency: [(6, 5), (7, 1), (5, 1), (8, 1)]

28、从列表中删除重复值

cities_list = ['Vienna', 'Paris', 'Seoul',"Amsterdam","Paris","Amsterdam","Paris"] cities_list = set(cities_list) print("After removing the duplicate values from the list:",list(cities_list))

29、找出两个列表之间的差异

cities_list1 = ['Vienna', 'Paris', 'Seoul',"Amsterdam", "Berlin", "London"] cities_list2 = ['Vienna', 'Paris', 'Seoul',"Amsterdam"] cities_set1 = set(cities_list1) cities_set2 = set(cities_list2) difference = list(cities_set1.symmetric_difference(cities_set2)) print(difference)

30、将两个不同的列表转换为一个字典

number = [1, 2, 3] cities = ['Vienna', 'Paris', 'Seoul'] result = dict(zip(number, cities)) print(result)


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:通过14个入门实战案例教大家快速学习Python编程语言(python从入门到实践和Python编程快速上手)
下一篇:Java查询时间段(startTime
相关文章

 发表评论

暂时没有评论,来抢沙发吧~