1. python 在列表、字典、集合中筛选数据
- 列表:filter函数、列表解析
- 字典:字典解析
- 集合:集合解析
'''
在列表、字典、集合中筛选数据
1. 列表:filter函数、列表解析
2. 字典:字典解析
3. 集合:集合解析
'''
def list_fiter():
'''
1. 列表:过滤列表中的负数
:return:
'''
# filter函数:
from random import randint
data = [randint(-10, 10) for _ in range(10)]
print(data)
data_filter = filter(lambda x: x >= 0, data)
data_positive = [_ for _ in data_filter]
print('filter函数')
print(data_positive)
# 列表解析
data_positive = [_ for _ in data if _ >= 0]
print('列表解析')
print(data_positive)
def dict_fiter():
'''
1. 字典:过滤列表中的负数
:return:
'''
# 字典解析:
from random import randint
data = {x: randint(-10, 10) for x in range(10)}
print(data)
data_positive = {k: v for k, v in data.items() if v >= 0}
print('字典解析')
print(data_positive)
def set_fiter():
'''
1. set:过滤列表中的负数
:return:
'''
# set解析:
from random import randint
data = (randint(-10, 10) for x in range(10))
print(data)
data_positive = {k for k in data if k >= 0}
print('set解析')
print(data_positive)
if __name__ == '__main__':
set_fiter()
2. 将字典按照value进行排序:
def dictValueSort1():
'''
使用zip转变为元组
:return:
'''
data = {x: randint(60, 100) for x in list('zbcdef')}
form_data = zip(data.values(), data.keys())
res = sorted(form_data)
print(res)
def dictValueSort2():
'''
内置函数
:return:
'''
data = {x: randint(60, 100) for x in list('zbcdef')}
print(data)
res = sorted(data.items(), key=lambda x: x[1])
print(res)
3. 多个字典的公共键
from random import randint, sample
def way1():
'''
使用字典的viewkeys()方法,得到一个字典keys的集合.
使用map函数,得到所有字典的keys的集合.
使用reduce函数,取所有字典的keys的集合的交集.
:return:
'''
from functools import reduce
# 少量字典数量数写法
common_key = set(s1.keys()) & set(s2.keys()) & set(s3.keys())
print(common_key)
# 多字典数目写法
common_key = reduce(lambda a, b: a & b, map(set, [s1.keys(), s2.keys(), s3.keys()]))
print(common_key)
if __name__ == '__main__':
s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s3 = {x: randint(1, 4) for x in sample('abcdefd', randint(3, 6))}
'''
{'d': 4, 'c': 4, 'b': 4, 'e': 1, 'f': 4}
{'c': 3, 'a': 2, 'b': 1, 'e': 2, 'g': 2}
{'b': 4, 'c': 1, 'd': 4, 'a': 1, 'e': 1, 'f': 3}
'''
way1()
4. 让字典保持有序
使用collection
包中的OrderedDict
功能。
from collections import OrderedDict
d = OrderedDict()
d['1'] = (1, 294)
d['2'] = (3, 219)
d['3'] = (2, 229)
网友评论