首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

分享25个实用的一行Python代码,你都用过吗?

入门教程、案例源码、学习资料、读者群

请访问:python666.cn

大家好,欢迎来到 Crossin的编程教室 !

在学习Python的过程当中,有很多复杂的任务其实只需要一行代码就可以解决,那么今天就来给大家介绍25个实用的一行Python代码,希望对大家能够有所帮助。

1.两个字典的合并

x = {'a': 1, 'b': 2}

y = {'c': 3, 'd': 4}

将两个字典合并起来,代码如下

x.update(y)

print(x)

output

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

2.两个列表的合并

x = ['a', 'b']

y = ['c', 'd', 'e']

将上面两个列表合并起来,代码如下

x.extend(y)

print(x)

output

['a', 'b', 'c', 'd', 'e']

当然除此之外,我们还有其他的方法来将两个列表合并起来,例如

x += y

print(x)

output

['a', 'b', 'c', 'd', 'e']

3.计算列表中元素出现的频率

主要是通过调用python当中的collections模块来实现,例如

from collections import Counter

my_list = ['a', 'b', 'b', 'a', 'a', 'a', 'c', 'c', 'b', 'd']

print(Counter(my_list).most_common())

output

[('a', 4), ('b', 3), ('c', 2), ('d', 1)]

若是我们想要出现频率最多的一个,也就是在上面代码的基础之上添加筛选第一个元素的操作即可

print(Counter(my_list).most_common()[0])

output

('a', 4)

出现频率最多的是元素a,总共出现了4次

当然要是在后面再添加一个[0],意思就是筛选出出现频率最多的元素

print(Counter(my_list).most_common()[0][0])

output

a

4.计算获得除法中的商和余数

一般我们若想取得除法当中的商和余数,一般是Python运算符号当中的//和/,而divmod方法则可以让我们同时获得除法运算当中的商和余数,代码如下

quotient, remainder = divmod(37, 5)

print(quotient, remainder)

output

7 2

5.计算得到列表当中长度最长的字符串

words = ['Python', 'is', 'awesome']

print(max(words, key=len))

output

awesome

6.将列表中的顺序倒转

words = ['Python', 'is', 'awesome']

reverse_words = words[::-1]

print(reverse_words)

output

['awesome', 'is', 'Python']

7.文件的读与写

我们先将数据写入到文件当中

data = 'Python is awesome'

with open('file.txt', 'a', newline='\n') as f: f.write(data)

那我们从刚生成的文件当中读取刚写入的数据,代码就是这么来写

data = [line.strip() for line in open("file.txt")]

print(data)

output

['Python is awesome']

8.将字典当中的键值对位置调换

staff = {'Data Scientist': 'Mike', 'Django Developer': 'Dylan'}

staff = {i:j for j, i in staff.items()}

print(staff)

output

{'Mike': 'Data Scientist', 'Dylan': 'Django Developer'}

9.将嵌套列表合并为一个列表

假设我们有这样的一个列表

l = [[1, 2, 3], [4, 5], [6], [7, 8], [9]]

而我们最终希望列表能够是

[1, 2, 3, 4, 5, 6, 7, 8, 9]

我们可以这么来做

flattened_list = [item for sublist in l for item in sublist

print(flattened_list)

output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

10.列表当中数据类型的转换

例如有下面的列表

['1', '2', '3']

我们要将其转换成整数类型,代码如下

print(list(map(int, ['1', '2', '3'])))

output

[1, 2, 3]

当然我们也可以将可以尝试转换成浮点数的类型,代码如下

print(list(map(float, ['1', 2, '3.0', 4.0, '5', 6])))

output

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

11.将列表转化成字典

cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']

cars_dict = dict(enumerate(cars))

print(cars_dict)

output

{0: 'Audi', 1: 'BMW', 2: 'Ford', 3: 'Tesla', 4: 'Volvo'}

12.将列表当中的重复元素去除

list(set(['a', 'a', 'b', 'a', 'c']))

output

['a', 'b', 'c']

13.从列表中筛选出特定元素

cars = ['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']

car_1 = [car for car in cars if car[0] == "A"]

print(car_1)

output

['Audi']

当然我们还可以通过调用Python当中的filter方法来实现,代码如下

car_1 = list(filter(lambda c: c[0] == 'A', cars))

得到的结果也和上述的一样

14.列表中的元素排序

numbers = [55, -30, 28, -36, 48, 20]

numbers.sort()

print(numbers)

output

[-36, -30, 20, 28, 48, 55]

当然我们也可以从大到小,这样的方式来排序,代码如下

numbers.sort(reverse=True)

numbers

output

[55, 48, 28, 20, -30, -36]

而对于字符串而言,我们可以根据首字母的字母表顺序来排序

cars = ['Ford', 'Tesla', 'BMW', 'Volvo', 'Audi']

cars.sort()

print(cars)

output

['Audi', 'BMW', 'Ford', 'Tesla', 'Volvo']

15.合并集合

set1 = {"1", "2", "5"}

set2 = {"4", "6", "7"}

set1.update(set2)

print(set1)

output

{'7', '6', '5', '2', '1', '4'}

16. 根据键来对字典进行排序

d = {'one': 1, 'three': 4, 'five': 8, 'six': 10}

result = {key: d[key] for key in sorted(d.keys())}

print(result)

output

{'five': 8, 'one': 1, 'six': 10, 'three': 4}

17. 根据键值来对字典进行排序

d = {'one': 15, 'three': 12, 'five': 8, 'six': 30}

result = {key: value for key, value in sorted(d.items(), key=lambda item: item[1])}

print(result)

output

{'five': 8, 'three': 12, 'one': 15, 'six': 30}

18. 替换字符串

"Python is a programming language. Python is awesome".replace("Python",'Java')

output

Java is a programming language. Java is awesome

19. 计算指定字符串出现的次数

a = 'python is a programming language. python is python.'

result = a.count('python')

print(result)

output

3

20. 将自定义方法作用在列表中的每个元素

from functools import reduce

reduce(lambda x, y: x*y, [2, 2, 3, 4])

output

48

21. 找到最大的那个数

find_max = lambda x,y: x if x > y else y

result = find_max(5,20)

output

20

22. 将矩阵转置

a = [[1, 2, 3],

[4, 5, 6],

[7, 8, 9]]

transposed = [list(i) for i in zip(*a)]

print(transposed)

output

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

23. 生成斐波纳契数列

斐波纳契数列指的是列表当中元素的值是由前两个元素的值的总和而来的,例如像是1, 1, 2, 3, 5, 8,13,要生成它的代码如下

fibo = [0, 1]

[fibo.append(fibo[-2]+fibo[-1]) for i in range(10)]

print(fibo)

output

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

24. 删除列表中的多个元素

mylist = [100, 200, 300, 400, 500]

del mylist[:3]

print(mylist)

output

[400, 500]

25. 多个if-else组合

目标是将下面多个if-else的组合,写在一行上面

x = 200

if x 

print("小于20")

elif x == 200:

print("等于200")

else:

print("大于20且不等于200")

我们也可以将多个if-else组合放在一行上面写

x = 200

print("小于20") if x 

作者:欣一

  • 发表于:
  • 原文链接https://page.om.qq.com/page/OzKNcsEIbWNrra4Wp47Yig_Q0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券