30个Python操作小技巧

1、列表推导

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

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

输出:

csharp
复制代码
 [1,3,5,7]

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

css
复制代码
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的起始位置)。当您希望根据索引编写代码时,循环计数器很方便。

perl
复制代码
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号以元组形式返回员工的名字和姓氏。

python
复制代码
# 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))
css
复制代码
Student = get_student(0)
print('first_name: {}, last_name: {}'.format(Student[0], Student[1]))
方法二、

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

python
复制代码
# 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))
css
复制代码
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<x<30。

你也许经常使用的是这种

复制代码
1<x and x<30

在python中,你可以这么使用

ini
复制代码
x = 5
print(1<x<30)

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

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

go
复制代码
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 特殊的用法。

bash
复制代码
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个最小的元素。

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

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

bash
复制代码
value = "Taha"
print(value * 5)  
print("-" * 21)

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

less
复制代码
cities= ['Vienna', 'Amsterdam', 'Paris', 'Berlin']
print(cities.index('Berlin'))

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

lua
复制代码
print("Analytics", end="")
print("Vidhya")
print("Analytics", end=" ")
print("Vidhya")
print('Data', 'science', 'blogathon', '12', sep=', ')

输出

复制代码
AnalyticsVidhya
Analytics Vidhya
Data, science, blogathon, 12

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

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

scss
复制代码
print(5_000_000_000_000)

print(7_543_291_635)

输出:

复制代码
5000000000000
7543291635

12、反转列表的切片

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

ini
复制代码
sentence = "Data science blogathon"
print(sentence[21:0:-1])

输出

复制代码
nohtagolb ecneics ata

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

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

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

ini
复制代码
list1 = [7, 9, 4]
list2 = [7, 9, 4]
print(list1 == list2) 
print(list1 is list2)
list3 = list1
print(list3 is list1)

输出

python
复制代码
True
False
True

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

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

输出

css
复制代码
{‘London’: 1, ‘Paris’: 2, ‘Tokyo’: 3, ‘Seol’: 4}

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

bash
复制代码
sentence = "Analytics Vidhya"
print(sentence.startswith("b"))
print(sentence.startswith("A"))

16、获得字符的Unicode

perl
复制代码
print(ord("T"))
print(ord("A")) 
print(ord("h")) 
print(ord("a"))

17、获取字典的键值对

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

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

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

输出:

ini
复制代码
[‘London’, ‘Vienna’, ‘Rome’, ‘Seoul’] After insert: [‘Berlin’, ‘London’, ‘Vienna’, ‘Rome’, ‘Seoul’]

19、Filter() 函数

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

python
复制代码
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)}")

输出:

ini
复制代码
Before filter: [8, 15, 25, 30, 34, 67, 90, 5, 12]
After filter: [25, 30, 34, 67, 90]

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

scss
复制代码
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))

输出:

yaml
复制代码
60
1200
72000

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

scss
复制代码
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、检查对象使用的内存大小

go
复制代码
import sys
mul = 5*6
print(sys.getsizeof(mul))

23、 Map() 函数

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

python
复制代码
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 函数。

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

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

less
复制代码
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 操作

ini
复制代码
set1 = {'Vienna', 'Paris', 'Seoul'}
set2 = {"Tokyo", "Rome",'Amsterdam'}
print(set1.union(set2))

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

scss
复制代码
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())

输出:

yaml
复制代码
Counter({6: 5, 7: 1, 5: 1, 8: 1})
Sort values according their frequency: [(6, 5), (7, 1), (5, 1), (8, 1)]

28、从列表中删除重复值

scss
复制代码
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、找出两个列表之间的差异

ini
复制代码
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、将两个不同的列表转换为一个字典

ini
复制代码
number = [1, 2, 3]
cities = ['Vienna', 'Paris', 'Seoul']
result = dict(zip(number, cities))
print(result)



Python 的迅速崛起对整个行业来说都是极其有利的 ,但“人红是非多”,导致它平添了许许多多的批评,不过依旧挡不住它火爆的发展势头。

如果你对Python感兴趣,想要学习python,这里给大家分享一份Python全套学习资料,都是我自己学习时整理的,希望可以帮到你,一起加油!

😝有需要的小伙伴,可以点击下方链接免费领取或者V扫描下方二维码免费领取🆓
点击这里

在这里插入图片描述

1️⃣零基础入门

① 学习路线

对于从来没有接触过Python的同学,我们帮你准备了详细的学习成长路线图。可以说是最科学最系统的学习路线,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
在这里插入图片描述

② 路线对应学习视频

还有很多适合0基础入门的学习视频,有了这些视频,轻轻松松上手Python~
在这里插入图片描述

③练习题

每节视频课后,都有对应的练习题哦,可以检验学习成果哈哈!
在这里插入图片描述

2️⃣国内外Python书籍、文档

① 文档和书籍资料

在这里插入图片描述

3️⃣Python工具包+项目源码合集

①Python工具包

学习Python常用的开发软件都在这里了!每个都有详细的安装教程,保证你可以安装成功哦!
在这里插入图片描述

②Python实战案例

光学理论是没用的,要学会跟着一起敲代码,动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。100+实战案例源码等你来拿!
在这里插入图片描述

③Python小游戏源码

如果觉得上面的实战案例有点枯燥,可以试试自己用Python编写小游戏,让你的学习过程中增添一点趣味!
在这里插入图片描述

4️⃣Python面试题

我们学会了Python之后,有了技能就可以出去找工作啦!下面这些面试题是都来自阿里、腾讯、字节等一线互联网大厂,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
在这里插入图片描述
在这里插入图片描述

5️⃣Python兼职渠道

而且学会Python以后,还可以在各大兼职平台接单赚钱,各种兼职渠道+兼职注意事项+如何和客户沟通,我都整理成文档了。
在这里插入图片描述

上述所有资料 ⚡️ ,朋友们如果有需要的,可以扫描下方👇👇👇二维码免费领取🆓
在这里插入图片描述






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值