Python高效编程技巧

时间:2024-10-28 08:06:55

如何在列表,字典,集合中根据条件筛选数据

1.过滤掉列表[-1,-2,-3,4,5,6]中的负数和0

方法1,for循环

data = [-1, -2, -3, 4, 5, 6]
res = []
for i in data:
    if i > 0:
        res.append(i)
print(res)

方法2 filter

data = [-1, -2, -3, 4, 5, 6]
res = filter(lambda x: x > 0, data)
print(list(res))

方法3列表解析

data = [-1, -2, -3, 4, 5, 6]
res = [x for x in data if x > 0]
print(res)

性能对比:列表解析优于filter优于for循环。

补充,生成随机数字列表:

from random import randint

data = [randint(-10, 10) for _ in range(10)]
print(data)  # [5, 6, 6, -10, 6, -10, -7, 5, 5, -9]

2.筛选出字典{'lcg':100,'xiaoming':50,'wang':89,'hong':93}中值高于90的项

dic = {'lcg': 100, 'xiaoming': 50, 'wang': 89, 'hong': 93}
res = {k: y for k, y in dic.items() if y > 90}
print(res)  # {'lcg': 100, 'hong': 93}

3.筛选出集合{6,7,8,9,66,77}中能被3整除的元素

s = {6, 7, 8, 9, 66, 77}
res = {i for i in s if i % 3 == 0}
print(res)  # {9, 66, 6}

如何为元祖中的每个元素命名,提高程序的可读性

Python高效编程技巧

像上面这样的用0,1,2索引的方式获取元祖中的元素,实际上很不容易理解,也不容易维护。

解决方案:

方案1,拆包

t = ('jim', 19, 'male', 'jim666@gmail.com')
NAME, AGE, SEX, EMAIL = 0, 1, 2, 3
print(t[NAME])  # jim

方案2,使用标准库里面的collections.namedtuple代替内置的tuple

from collections import namedtuple

Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
# s = Student(name='jim',age= 19, sex='male', email='jim666@gmail.com')
s = Student('jim', 19, 'male', 'jim666@gmail.com')
print(s.name)  # jim
print(s.age)   # 19
print(s)       # Student(name='jim', age=19, sex='male', email='jim666@gmail.com')
print(isinstance(s,tuple)) # True

如何统计出序列中元素出现频度

Python高效编程技巧

1.使用collections.Counter对象。将序列传入Counter构造器,得到对象是元素额度的字典

Counter.most_common(n)方法得到频度最高的n个元素的列表。

from random import randint

data = [randint(0, 10) for _ in range(20)]
print(data)  # [6, 2, 10, 5, 10, 9, 3, 10, 1, 6, 9, 9, 3, 4, 7, 3, 0, 7, 10, 0]

from collections import Counter

c = Counter(data)
print(c)                # Counter({10: 4, 9: 3, 3: 3, 6: 2, 7: 2, 0: 2, 2: 1, 5: 1, 1: 1, 4: 1})
print(c.most_common())  # [(10, 4), (9, 3), (3, 3), (6, 2), (7, 2), (0, 2), (2, 1), (5, 1), (1, 1), (4, 1)]
print(c.most_common(3)) # [(10, 4), (9, 3), (3, 3)]

如何根据字典中值的大小,对字典中的项进行排序

1.使用内置函数sorted

# 首先构造一个字典
from random import randint

dic = {k: randint(60, 100) for k in 'abcdefg'}
print(dic)  # {'a': 82, 'b': 64, 'c': 87, 'd': 75, 'e': 65, 'f': 64, 'g': 79}

# sorted的作用就是对序列进行排序
print(sorted([1, 3, 5, 2, 4, 6]))  # [1, 2, 3, 4, 5, 6]

print(sorted(dic.items(), key=lambda x: x[1]))
# [('b', 64), ('f', 64), ('e', 65), ('d', 75), ('g', 79), ('a', 82), ('c', 87)]

  

Python高效编程技巧