常用一行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)
print(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 < 20:
    print("小于20")
elif x == 200:
    print("等于200")
else:
    print("大于20且不等于200")

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

x = 200
print("小于20") if x < 20 else print("等于200") if x == 200 else print("大于20且不等于200")

参考博客

收藏 | 25个好用到爆的一行Python代码

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值