3.数据结构和算法(三)

3.数据结构和算法(三)

筛选序列中的元素

使用列表推导式来进行筛选

>>> items=[3,2,4,5,2,2,3,9,-1,-2,-3,-4,-5]
>>> [n for n in items if n>0]
[3, 2, 4, 5, 2, 2, 3, 9]
>>> [n for n in items if n<=0]
[-1, -2, -3, -4, -5]

如果数据非常大,可以使用生成器

items=[3,2,4,5,2,2,3,9,-1,-2,-3,-4,-5]

pos = (n for n in items if n>0)

for i in pos:
    print(i,end=" ")

# 3 2 4 5 2 2 3 9

还可以将处理筛选逻辑的代码放到单独的函数中,然后使用内建的filter()

items=[3,2,4,5,2,2,3,9,-1,-2,-3,-4,-5]

def is_int(val):
    if val%2==0:
        return True     #返回True代表确定
    else:
        return False    #返回False代表不确定

ivals = filter(is_int,items)

for i in ivals:
    print(i,end=" ")

# 2 4 2 2 -2 -4
items=[3,2,4,5,9,-1,-2,-3,-4,-5]

#进行元素替换
maths = [ n+1 for n in items]
print(maths)

#元素替换
zero = [n if n>0 else 0 for n in items]
print(zero)

# [4, 3, 5, 6, 10, 0, -1, -2, -3, -4]
# [3, 2, 4, 5, 9, 0, 0, 0, 0, 0]
from itertools import compress

address =[
    "5412",
    "5420",
    "5415",
    "5421",
]

counts =[-1,2,-1,2]
more = [n>0 for n in counts]

#compress返回一个迭代器,可以使用list进行转换
result = list(compress(address,more))
print(result)

#['5420', '5421']

从字典中提取子集

可以使用字典推导式来提取字典子集

dicts ={
    'key1':3,
    'key2':4,
    'key3':5,
    'key4':6
}

stock = {key:value for key,value in dicts.items() if value>4}

print(stock)

#{'key3': 5, 'key4': 6}

将名称映射到序列的元素中

使用namedtuple()可以将名称映射到序列中的元素

from collections import namedtuple

sub = namedtuple('sub',['one','two','three','four','five'])
sub_prototype=sub(1,2,3,4,5)

print(sub_prototype.one,end =" ")
print(sub_prototype.two)
# 1 2

如果需要修改属性内容,可以使用_replace()来进行替换

from collections import namedtuple

sub = namedtuple('sub',['one','two','three','four','five'])
sub_prototype=sub(1,2,3,4,5)

sub_prototype=sub_prototype._replace(five=6)
print(sub_prototype)

#sub(one=1, two=2, three=3, four=4, five=6)

同时对数据做转换和换算

可以使用生成器表达式

items = [12,3,4,1,12,34]

result = sum(x*x for x in items)

#与上一个表达式相同,省略掉多余的括号,能够加快程序的运行速度
#result =sum([x*x for x in items])

print(result)

# 1470

将多个映射合并为单个映射

from collections import ChainMap

a ={'x':1,'z':3}
b ={'y':2,'z':4}
c =ChainMap(a,b)

print(c['x'],end=" ")
print(c['y'],end=" ")
print(c['z'])

# 1 2 3

如果具有重复的值,那么这里会采用第一个映射中所对应的值

from collections import ChainMap

a ={'x':1,'z':3}
b ={'y':2,'z':4}
c =ChainMap(a,b)

#添加一个新的映射
c =c.new_child()
c['a']=3

print(c)
#ChainMap({'a': 3}, {'x': 1, 'z': 3}, {'y': 2, 'z': 4})

ChainMap不会和原来的数据进行绑定,因此改变原来字典的值不会对ChainMap产生影响

© 版权声明
THE END
喜欢就支持以下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容