python 入门笔记实例篇(1) 数据结构与算法

本文介绍了Python中数据结构与算法的应用,包括使用占位符忽略部分值、*表达式分配变量、deque模块保留最近元素、nlargest和nsmallest模块查找最大或最小元素、defaultdict处理字典键映射多个值、zip排序、查找字典相同点、set和lambda删除序列重复元素、slice切片、Counter计数、itemgetter和groupby进行字典列表排序和分组等实用技巧。
摘要由CSDN通过智能技术生成

Case1 : 只想保留部分值,丢弃其他的值,可以使用任意变量名去占位,如”_”

data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]

[ _,mm,_,nn]= data

print(mm)

print(nn)

-------------result-------------

50

(2012, 12, 21)

 

Case2 : *表达式(赋值给n个变量)

(可以用*_表示多个废弃变量)

records = [('foo', 1, 2),('bar', 'hello'),('foo', 3, 4)]

def do_foo(x, y):

    print('foo', x, y)

def do_bar(s):

    print('bar', s)

#迭代三次

for tag, *args in records:

    if tag == 'foo':

        #第一个变量值是foo,*args有两个变量值

        do_foo(*args)

    elif tag == 'bar':

        # 第一个变量值是bar,*args有一个变量值

        do_bar(*args)

-------------result-------------

foo 1 2

bar hello

foo 3 4

 

Case3 : deque模块(保留最后n个元素)

from collections import deque

#使用deque模块,在序列的前后你都可以执行添加或删除操作

# 当限制长度的deque增加超过限制数的项时,另一边的项会自动删除

def search(lines, pattern, history=5):

    #新建一个长度是5的deque列表

    previous_lines = deque(maxlen=history)

    # 迭代所有行的数据

    for line in lines:

        #如果匹配值在这一行,追加这一行数据到列表

        if pattern in line:

            previous_lines.append(line)

    #yield 相当于return,当时不会接受程序,会继续迭代

    #返回迭代完成后,previous_lines列表最终的5行数据

    print(previous_lines)

    yield previous_lines

    print("\n---end---")

if __name__ == '__main__':

    with open(r'abc.txt') as f:

        #找到文件中含有python数据的行数据,添加到列表中,列表最大元素个数为5,迭代次数为总行数

        for prevlines in search(f, 'python', 5):

            #pline是列表prevlines中的元素,去掉后面的\n,分别返回每一行数据

            for pline in prevlines:

                print(pline, end='')

-------------result-------------

deque(['ccccccccccccccpython\n', 'ddpythonddddddddddd\n', 'hello!python!word!\n', '2019python0101\n', 'python打开文件'], maxlen=5)

ccccccccccccccpython

ddpythonddddddddddd

hello!python!word!

2019python0101

python打开文件

---end---

 

Case4 : 排序+nlargest和nsmallest模块(查找最大或最小的 N 个元素)

import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

#正序

print(sorted(nums))

#倒序

print(list(reversed(sorted(nums))))

#取最大的前三个数

print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]

#取最小的前三个数

print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

-------------result-------------

[-4, 1, 2, 2, 7, 8, 18, 23, 23, 37, 42]

[42, 37, 23, 23, 18, 8, 7, 2, 2, 1, -4]

[42, 37, 23]

[-4, 1, 2]

 

Case5 : defaultdict(字典中的键映射多个值)

from collections import defaultdict

pairs = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]

d = defaultdict(list)

print(d)

for key, value in pairs:

    d[key].append(value)

print(d)

print(d['red'])

-------------result-------------

defaultdict(<class 'list'>, {})

defaultdict(<class 'list'>, {'red': [1, 3, 1], 'blue': [2, 4, 4]})

[1, 3, 1]

 

Case6 : zip(根据字典值排序)

prices = {'ACME': 45.23,'AAPL': 612.78,'IBM': 205.55,'HPQ': 37.20,'FB': 10.75}

#字典排序,求最大值,最小值需要使用zip先将键和值反转过来,才会对值进行计算

prices_sorted = sorted(zip(prices.values(), prices.keys()))

print(prices_sorted)

min_price = min(zip(prices.values(), prices.keys()))

print(min_price )

max_price = max(zip(prices.values(), prices.keys()))

print(max_price)

-------------result-------------

[(10.75, 'FB'), (37.2, 'HPQ'), (45.23, 'ACME'), (205.55, 'IBM'), (612.78, 'AAPL')]

(10.75, 'FB')

(612.78, 'AAPL')

 

Case7 : 查找两字典的相同点

a = { 'x' : 1,'y' : 2,'z' : 3}

b = {'w' : 10,'x' : 11,'y' : 2}

c = a.keys() - b.keys()

print(c)

d = a.keys() - c

print(d)

e={}

for i in d:

    e[i]=a[i]

print(e)

-------------result-------------

{'z'}

{'x', 'y'}

{'x': 1, 'y': 2}

 

Case8 : set, lambda (删除序列相同元素并保持顺序)

def dedupe(items, key = None):

    #set()删除列的重复数据

    # 创建空集合{},集合内容相不同新增,相同则删除后一个

    seen = set()

    #items此处代表列表a,item是便利出来的每一个字典

    for item in items:

        #如果未输入key值,val等于列表第一个字典;如果输入key值,val等于(d['x'],d['y']))

        if key is None :

            val = tuple(item.values())

        else :

            #val是(d['x'],d['y'])的值组成的

            val=key(item)

        #如果此次遍历的(d['x'],d['y'])的值不在seen中,就添加该值到seen,并返回该字典到列表b中

        if val not in seen:

            yield  item

            seen.add(val)

            print(val)

a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]

#lambda匿名函数,:前面是参数,:后面是返回值

该函数代表输入一个字典d,返回(d['x'],d['y'])的值

b=list(dedupe(a , key = lambda d : (d['x'],d['y'])))

print(b)

c = list(dedupe(a))

print(c)

d=list(dedupe(a, key=lambda d: d['x']))

print(d)

-------------result-------------

(1, 2)

(1, 3)

(2, 4)

[{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]

(1, 2)

(1, 3)

(2, 4)

[{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]

1

2

[{'x': 1, 'y': 2}, {'x': 2, 'y': 4}]

 

Case9 : slice() 切片

items = [0, 1, 2, 3, 4, 5, 6]

a = slice(1,6,2)

print(items[a])

print(a.start)

print(a.stop)

print(a.step)

items[a] = ['aa','bb','cc']

print(items )

-------------result-------------

[1, 3, 5]

1

6

2

[0, 'aa', 2, 'bb', 4, 'cc', 6]

 

Case10 : Counter() 对出现频率最高的元素进行计数

from collections import Counter

words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the']

word_counts = Counter(words)

# 出现频率最高的3个单词

top_three = word_counts.most_common(3)

print(top_three)

-------------result-------------

[('eyes', 5), ('the', 4), ('look', 2)]

 

Case11 : itemgetter和groupby (通过某个关键字排序字典列表, 对字典列表进行分组)

from operator import itemgetter

from itertools import groupby

rows = [{'fname': 'Brian', 'lname': 'Jones', 'uid': 1002},

        {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},

        {'fname': 'John', 'lname': 'Beazley', 'uid': 1002}]

rows_by_fname = sorted(rows, key=itemgetter('fname'))

rows_by_uid = sorted(rows, key=itemgetter('uid'))

print(rows_by_fname)

print(rows_by_uid)

for  uid , mm  in  groupby(rows_by_uid , key=itemgetter('uid')):

    #groupby()函数扫描整个序列并且查找连续相同值(需要先排序)的元素序列。

    # 迭代的时会返回一个值和一个迭代器对象,这个迭代器对象可以生成分组后的数据

    print(uid)

    for i in mm:

        print(' ', i)

-------------result-------------

[{'fname': 'Brian', 'lname': 'Jones', 'uid': 1002}, {'fname': 'John', 'lname': 'Cleese', 'uid': 1001}, {'fname': 'John', 'lname': 'Beazley', 'uid': 1002}]

[{'fname': 'John', 'lname': 'Cleese', 'uid': 1001}, {'fname': 'Brian', 'lname': 'Jones', 'uid': 1002}, {'fname': 'John', 'lname': 'Beazley', 'uid': 1002}]

1001

  {'fname': 'John', 'lname': 'Cleese', 'uid': 1001}

1002

  {'fname': 'Brian', 'lname': 'Jones', 'uid': 1002}

  {'fname': 'John', 'lname': 'Beazley', 'uid': 1002}

 

Case12 : 字典/列表提取子集

mylist = [1, 4, -5, 10, -7, 2, 3, -1]

#返回值 + for ... in... +  (if)

xx =[n for n in mylist if n > 0]

print(xx)

prices = {'ACME': 45.23,'AAPL': 612.78,'IBM': 205.55,'HPQ': 37.20,'FB': 10.75}

aa={key : value for key, value in prices.items() if value > 200}

print(aa)

-------------result-------------

[1, 4, 10, 2, 3]

{'AAPL': 612.78, 'IBM': 205.55}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值