python中各种数据结构与算法的解决技巧

一、如何在列表,字典,集合中根据条件筛选数据
1、过滤掉【3,9,-1,10,20,-2】中的负数
方案一:
>>> l = [randint(-10,10) for _ in range(10)]
>>> print(l)
[0, 3, 4, -7, 6, 4, -5, -4, -8, -1]
>>> [x for x in l if x>=0]
[0, 3, 4, 6, 4]
方案二:
>>> [x for x in l if x>=0]
[0, 3, 4, 6, 4]
>>> filter(lambda x: x>=0, l)
<filter object at 0x109dcf198>
>>> list(filter(lambda x: x>=0, l))
[0, 3, 4, 6, 4]

2、筛出字典{'lilei':79,'jim':88,'lucy':92...}中值高于90的项

>>> d = {'student%d' % i :randint(50,100) for i in range(1,20)}
... print(d)
{'student1': 61, 'student2': 62, 'student3': 100, 'student4': 53, 'student5': 52, 'student6': 69, 'student7': 53, 'student8': 72, 'student9': 92, 'student10': 90, 'student11': 98, 'student12': 58, 'student13': 67, 'student14': 70, 'student15': 74, 'student16': 71, 'student17': 62, 'student18': 76, 'student19': 69}
>>> {k:v for k ,v in d.items() if v >=90}
{'student3': 100, 'student9': 92, 'student10': 90, 'student11': 98}
>>> g = filter(lambda item: item[1] >=90,d.items())
>>> print(dict(g))
{'student3': 100, 'student9': 92, 'student10': 90, 'student11': 98}

 

3、筛出集合{77,89,32,20}中能被3整除的元素

>>> s = {randint(0,20) for _ in range(20)} #这里的下划线是给读者看的,
... print(s)
{0, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 15, 18, 19, 20}
>>> {x for x in s if x % 3 ==0}
{0, 3, 9, 12, 15, 18}

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

方案1:定义一系列数值常量或枚举类型
例1:
name,age,sex,email = range(4)

def xxx_func(student):
    if student[age] < 18:
        print("pass")
    if student[sex] =='male':
        print("pass")

student = ('Jim',16,'male','jim8721@gmail.com')
print(xxx_func(student))



例2:
from enum import IntEnum
s = ('Jim',16,'male','jim8721@gmail.com')
t = (34,'guoyan')

class StudentEnum(IntEnum):
    name = 0
    age = 1
    sex = 2
    email = 3

print(s[StudentEnum.name])
print(s[StudentEnum.age])

方案2:使用标准库中collections.nameedtuple 替代内置tuple


>>> from collections import namedtuple
>>> Student = namedtuple('Student',['name','age','sex','email'])
>>> s2 = Student('Jim',16,'male','jim8721@gmail.com')
>>> print(s2)
Student(name='Jim', age=16, sex='male', email='jim8721@gmail.com')
>>> s2.name
'Jim'
>>> s2.age
16
三、如何根据字典中值的大小,对字典中的项排序

某班英语成绩以字典形式存储为:{'lilei':79,'jim':88,'lucy':92},如何根据成绩高低,计算学生排名

解决方案:将字典中的各项转换为元组,使用内置函数sorted排序(元组可以比较大小)
方案1: 将字典中的项转化为(值,键)元组。(列表解析或zip)

>>> from random import randint
>>> d = {k : randint(60,100) for k in 'abcdefgh'}
... print(d)
{'a': 66, 'b': 64, 'c': 71, 'd': 98, 'e': 80, 'f': 76, 'g': 75, 'h': 100}

列表解析解决:
l = [(v,k) for k,v in d.items()]
>>> print(l)
[(66, 'a'), (64, 'b'), (71, 'c'), (98, 'd'), (80, 'e'), (76, 'f'), (75, 'g'), (100, 'h')]
>>> print(sorted(l,reverse=True))
[(100, 'h'), (98, 'd'), (80, 'e'), (76, 'f'), (75, 'g'), (71, 'c'), (66, 'a'), (64, 'b')]

zip解决:
s = list(zip(d.values(),d.keys()))
>>> print(sorted(s,reverse=True))
[(100, 'h'), (98, 'd'), (80, 'e'), (76, 'f'), (75, 'g'), (71, 'c'), (66, 'a'), (64, 'b')]

匿名函数解决:
p = sorted(d.items(),key=lambda item: item[1],reverse=True)
print(p)

排好序后加入排名,用enumerate枚举
>>> list(enumerate(p,1))
[(1, (100, 'h')), (2, (98, 'd')), (3, (80, 'e')), (4, (76, 'f')), (5, (75, 'g')), (6, (71, 'c')), (7, (66, 'a')), (8, (64, 'b'))]
>>> for i ,(k,v) in enumerate(p,1):
...     print(i,k,v)
...     
1 100 h
2 98 d
3 80 e
4 76 f
5 75 g
6 71 c
7 66 a
8 64 b
四、如何统计序列中元素的频度
1、某随机序列[12,5,6,4,6,5,5,7]中,找到出现次数最高的3个元素,它们出现次数是多少?

解决方案1:将序列转换为字典{元素:频度},根据字典中的值排序 
>>> data = [randint(0,20) for _ in range(30)]
>>> data
[17, 19, 10, 4, 10, 12, 9, 12, 4, 13, 8, 0, 16, 9, 11, 6, 5, 15, 6, 13, 12, 10, 0, 18, 8, 1, 5, 3, 18, 12]
>>> import heapq
>>> d = dict.fromkeys(data,0)
>>> d
{17: 0, 19: 0, 10: 0, 4: 0, 12: 0, 9: 0, 13: 0, 8: 0, 0: 0, 16: 0, 11: 0, 6: 0, 5: 0, 15: 0, 18: 0, 1: 0, 3: 0}
>>> for x in data:
...     d[x] +=1
...     
>>> d
{17: 1, 19: 1, 10: 3, 4: 2, 12: 4, 9: 2, 13: 2, 8: 2, 0: 2, 16: 1, 11: 1, 6: 2, 5: 2, 15: 1, 18: 2, 1: 1, 3: 1}
>>> heapq.nlargest(3,((v,k) for k,v in d.items()) )
[(4, 12), (3, 10), (2, 18)]

解决方案2:使用标准库collections中的Counter对象
>>> from collections import Counter
>>> data
[17, 19, 10, 4, 10, 12, 9, 12, 4, 13, 8, 0, 16, 9, 11, 6, 5, 15, 6, 13, 12, 10, 0, 18, 8, 1, 5, 3, 18, 12]
>>> Counter(data)
Counter({12: 4, 10: 3, 4: 2, 9: 2, 13: 2, 8: 2, 0: 2, 6: 2, 5: 2, 18: 2, 17: 1, 19: 1, 16: 1, 11: 1, 15: 1, 1: 1, 3: 1})
>>> c = Counter(data)
>>> c.most_common(3)   #前三位
[(12, 4), (10, 3), (4, 2)]

2、对某英文文章的单词,进行词频统计,找到出现次数最高的10个单词,它们出现次数是多少?

>>> text = open('/Users/zhangsan/Desktop/dd/test.txt').read()
>>> text
"2019-07-03 19:04:05,536 INFO o.a.j.u.JMeterUtils: Setting Locale to en_EN\n2019-07-03 19:04:05,657 INFO o.a.j.JMeter: Loading user properties from: /Users/zhangshan/Desktop/测试工具/性能测试工具/apache-jmeter-5.0/bin/user.properties\n2019-07-03 19:04:05,662 INFO o.a.j.JMeter: Loading system properties from: /Users/zhangshan/Desktop/测试工具/性能测试工具/apache-jmeter-5.0/bin/system.properties\n2019-07-03 19:04:05,687 INFO o.a.j.JMeter: Copyright (c) 1998-2018 The Apache Software Foundation\n2019-07-03 19:04:05,688 INFO o.a.j.JMeter: Version 5.0 r1840935\n2019-07-03 19:04:05,688 INFO o.a.j.JMeter: java.version=1.8.0_191\n2019-07-03 19:04:05,689 INFO o.a.j.JMeter: java.vm.name=Java HotSpot(TM) 64-Bit Server VM\n2019-07-03 19:04:05,690 INFO o.a.j.JMeter: os.name=Mac OS X\n2019-07-03 19:04:05,690 INFO o.a.j.JMeter: os.arch=x86_64\n2019-07-03 19:04:05,690 INFO o.a.j.JMeter: os.version=10.13.1\n2019-07-03 19:04:05,690 INFO o.a.j.JMeter: file.encoding=UTF-8\n2019-07-03 19:04:05,690 INFO o.a.j.JMeter: Max memory     =1073741824\n2019-07-03 19:04:05,691 INFO o.a.j.JMeter: Available Processors =4\n2019-07-03 19:04:05,724 INFO o.a.j.JMeter: Default Locale=English (EN)\n2019-07-03 19:04:05,725 INFO o.a.j.JMeter: JMeter  Locale=English (EN)\n2019-07-03 19:04:05,725 INFO o.a.j.JMeter: JMeterHome=/Users/zhangshan/Desktop/测试工具/性能测试工具/apache-jmeter-5.0\n2019-07-03 19:04:05,726 INFO o.a.j.JMeter: user.dir  =/Users/zhangshan\n2019-07-03 19:04:05,726 INFO o.a.j.JMeter: PWD       =/Users/zhangshan\n2019-07-03 19:04:09,115 INFO o.a.j.JMeter: IP: 10.241.137.31 Name: sh-zhangshan.local FullName: 10.241.137.31\n2019-07-03 19:04:15,842 INFO o.a.j.g.a.LookAndFeelCommand: Installing Darcula LAF\n2019-07-03 19:04:15,950 INFO o.a.j.g.a.LookAndFeelCommand: Using look and feel: com.bulenkov.darcula.DarculaLaf [Darcula]\n2019-07-03 19:04:15,950 INFO o.a.j.JMeter: Setting LAF to: com.bulenkov.darcula.DarculaLaf\n2019-07-03 19:04:16,232 INFO o.a.j.JMeter: Loaded icon properties from org/apache/jmeter/images/icon.properties\n2019-07-03 19:04:18,805 INFO o.a.j.e.u.CompoundVariable: Note: Function class names must contain the string: '.functions.'\n2019-07-03 19:04:18,805 INFO o.a.j.e.u.CompoundVariable: Note: Function class names must not contain the string: '.gui.'\n2019-07-03 19:04:23,067 INFO o.j.r.JARSourceHTTP: Requesting https://jmeter-plugins.org/repo/?installID=mac_os_x-0591934f4a05feae4cf4c38991a9bbf8-gui\n2019-07-03 19:04:27,846 INFO o.a.j.p.h.s.HTTPSamplerBase: Parser for text/html is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser\n2019-07-03 19:04:27,847 INFO o.a.j.p.h.s.HTTPSamplerBase: Parser for application/xhtml+xml is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser\n2019-07-03 19:04:27,848 INFO o.a.j.p.h.s.HTTPSamplerBase: Parser for application/xml is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser\n2019-07-03 19:04:27,848 INFO o.a.j.p.h.s.HTTPSamplerBase: Parser for text/xml is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser\n2019-07-03 19:04:27,848 INFO o.a.j.p.h.s.HTTPSamplerBase: Parser for text/vnd.wap.wml is org.apache.jmeter.protocol.http.parser.RegexpHTMLParser\n2019-07-03 19:04:27,848 INFO o.a.j.p.h.s.HTTPSamplerBase: Parser for text/css is org.apache.jmeter.protocol.http.parser.CssParser\n2019-07-03 19:04:29,467 INFO o.a.j.e.KeyToolUtils: keytool found at 'keytool'\n2019-07-03 19:04:29,468 INFO o.a.j.p.h.p.ProxyControl: HTTP(S) Test Script Recorder SSL Proxy will use keys that support embedded 3rd party resources in file /Users/zhangshan/Desktop/测试工具/性能测试工具/apache-jmeter-5.0/bin/proxyserver.jks\n2019-07-03 19:04:29,891 INFO o.a.j.s.FileServer: Default base='/Users/zhangshan'\n2019-07-03 19:04:31,087 INFO o.j.r.PluginManager: Plugins Status: [jpgc-plugins-manager=1.3, jmeter-core=5.0, jmeter-ftp=5.0, jmeter-http=5.0, jmeter-jdbc=5.0, jmeter-jms=5.0, jmeter-junit=5.0, jmeter-java=5.0, jmeter-ldap=5.0, jmeter-mail=5.0, jmeter-mongodb=5.0, jmeter-native=5.0, jmeter-tcp=5.0, jmeter-components=5.0]\n2019-07-03 19:04:31,360 INFO o.a.j.s.SampleResult: Note: Sample TimeStamps are START times\n2019-07-03 19:04:31,360 INFO o.a.j.s.SampleResult: sampleresult.default.encoding is set to UTF-8\n2019-07-03 19:04:31,361 INFO o.a.j.s.SampleResult: sampleresult.useNanoTime=true\n2019-07-03 19:04:31,362 INFO o.a.j.s.SampleResult: sampleresult.nanoThreadSleep=5000\n2019-07-03 19:07:07,022 INFO o.a.j.e.StandardJMeterEngine: Running the test!\n2019-07-03 19:07:07,025 INFO o.a.j.s.SampleEvent: List of sample_variables: []\n2019-07-03 19:07:07,025 INFO o.a.j.s.SampleEvent: List of sample_variables: []\n2019-07-03 19:07:07,031 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*)\n2019-07-03 19:07:07,379 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group\n2019-07-03 19:07:07,380 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group Thread Group.\n2019-07-03 19:07:07,381 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error\n2019-07-03 19:07:07,381 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=1 perThread=1000.0 delayedStart=false\n2019-07-03 19:07:07,388 INFO o.a.j.t.ThreadGroup: Started thread group number 1\n2019-07-03 19:07:07,388 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started\n2019-07-03 19:07:07,392 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1\n2019-07-03 19:07:07,410 INFO o.a.j.p.h.s.HTTPHCAbstractImpl: Local host = sh-zhangshan.local\n2019-07-03 19:07:07,426 INFO o.a.j.p.h.s.HTTPHC4Impl: HTTP request retry count = 0\n2019-07-03 19:07:07,492 INFO o.a.j.t.JMeterThread: Thread is done: Thread Group 1-1\n2019-07-03 19:07:07,492 INFO o.a.j.t.JMeterThread: Thread finished: Thread Group 1-1\n2019-07-03 19:07:07,493 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test\n2019-07-03 19:07:07,494 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)\n2019-07-03 19:07:10,370 INFO o.a.j.e.StandardJMeterEngine: Running the test!\n2019-07-03 19:07:10,371 INFO o.a.j.s.SampleEvent: List of sample_variables: []\n2019-07-03 19:07:10,373 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*)\n2019-07-03 19:07:10,616 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group\n2019-07-03 19:07:10,617 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group Thread Group.\n2019-07-03 19:07:10,617 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error\n2019-07-03 19:07:10,617 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=1 perThread=1000.0 delayedStart=false\n2019-07-03 19:07:10,618 INFO o.a.j.t.ThreadGroup: Started thread group number 1\n2019-07-03 19:07:10,619 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started\n2019-07-03 19:07:10,620 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1\n2019-07-03 19:07:10,624 INFO o.a.j.t.JMeterThread: Thread is done: Thread Group 1-1\n2019-07-03 19:07:10,624 INFO o.a.j.t.JMeterThread: Thread finished: Thread Group 1-1\n2019-07-03 19:07:10,625 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test\n2019-07-03 19:07:10,625 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)\n2019-07-03 19:07:58,789 INFO o.a.j.e.StandardJMeterEngine: Running the test!\n2019-07-03 19:07:58,790 INFO o.a.j.s.SampleEvent: List of sample_variables: []\n2019-07-03 19:07:58,793 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*)\n2019-07-03 19:07:58,961 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group\n2019-07-03 19:07:58,961 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group Thread Group.\n2019-07-03 19:07:58,961 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error\n2019-07-03 19:07:58,961 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=1 perThread=1000.0 delayedStart=false\n2019-07-03 19:07:58,962 INFO o.a.j.t.ThreadGroup: Started thread group number 1\n2019-07-03 19:07:58,962 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started\n2019-07-03 19:07:58,963 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1\n2019-07-03 19:07:58,966 INFO o.a.j.t.JMeterThread: Thread is done: Thread Group 1-1\n2019-07-03 19:07:58,966 INFO o.a.j.t.JMeterThread: Thread finished: Thread Group 1-1\n2019-07-03 19:07:58,969 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test\n2019-07-03 19:07:58,970 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)\n"
>>> import re
>>> word_list = re.split('\W+',text)
>>> c2 = Counter(word_list)
>>> c2.most_common(10)
[('07', 147), ('2019', 85), ('03', 85), ('19', 85), ('INFO', 85), ('o', 85), ('a', 85), ('j', 85), ('04', 40), ('1', 39)]
五、如何快速找到多个字典中的公共键(key)
解决方案1:
>>> from random import randint,sample >>> sample('abcdefgh',3) ['g', 'e', 'h'] >>> sample('abcdefgh',randint(3,6)) ['a', 'e', 'b', 'c', 'g', 'f'] >>> d1 = {k : randint(1,4) for k in sample('abcdefgh',randint(3,6))} >>> d1 {'c': 4, 'f': 1, 'h': 4} >>> d2 = {k : randint(1,4) for k in sample('abcdefgh',randint(3,6))} >>> d3 = {k : randint(1,4) for k in sample('abcdefgh',randint(3,6))} >>> d2 {'h': 2, 'b': 3, 'f': 2, 'g': 4, 'c': 2} >>> d3 {'c': 1, 'd': 3, 'f': 1, 'a': 2, 'e': 3, 'b': 2} >>> [k for k in d1 if k in d2 and k in d3] ['c', 'f'] >>> ds = [d1,d2,d3] >>> [k for k in ds[0] if all(map(lambda d : k in d,ds[1:]))] ['c', 'f'] 解决方案2:利用集合(set)的交集操作 1、使用字典的keys()方法,得到一个字典keys的集合 2、使用map函数,得到每个字典keys的集合 3、使用reduce函数,取所有字典的keys集合的交集 >>> from random import randint,sample >>> sample('abcdefgh',3) ['g', 'e', 'h'] >>> sample('abcdefgh',randint(3,6)) ['a', 'e', 'b', 'c', 'g', 'f'] >>> d1 = {k : randint(1,4) for k in sample('abcdefgh',randint(3,6))} >>> d1 {'c': 4, 'f': 1, 'h': 4} >>> d2 = {k : randint(1,4) for k in sample('abcdefgh',randint(3,6))} >>> d3 = {k : randint(1,4) for k in sample('abcdefgh',randint(3,6))} >>> d2 {'h': 2, 'b': 3, 'f': 2, 'g': 4, 'c': 2} >>> d3 {'c': 1, 'd': 3, 'f': 1, 'a': 2, 'e': 3, 'b': 2} >>> [k for k in d1 if k in d2 and k in d3] ['c', 'f'] >>> ds = [d1,d2,d3] >>> [k for k in ds[0] if all(map(lambda d : k in d,ds[1:]))] ['c', 'f'] >>> d1.keys() dict_keys(['c', 'f', 'h']) >>> d2.keys() dict_keys(['h', 'b', 'f', 'g', 'c']) >>> list(map(dict.keys,ds)) [dict_keys(['c', 'f', 'h']), dict_keys(['h', 'b', 'f', 'g', 'c']), dict_keys(['c', 'd', 'f', 'a', 'e', 'b'])] >>> from functools import reduce >>> reduce(lambda a,b:a & b,map(dict.keys,ds)) {'f', 'c'}
六、如何让字典保持有序
实际案例:
某编程竞赛系统,对参赛选手编程解题进行计时,选手完成题目后,把该选手解题用时记录到字典中,以便赛后按选手名查询成绩
{'lilei':(2,43),'hanmeimei':(5,52),'jim':(1,39)...}
比赛结束后,需按排名顺序依次打印选手成绩,如何实现?

字典本身是无序的
players = list('abcdefgh')
>>> from collections import shuffle    #一个洗盘函数,可以把列表打乱
>>> from random import shuffle
>>> shuffle(players)
>>> players
['h', 'f', 'b', 'c', 'g', 'a', 'd', 'e']
>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> for i ,p in enumerate(players,1):
...     od[p] = i 
>>> od
OrderedDict([('h', 1), ('f', 2), ('b', 3), ('c', 4), ('g', 5), ('a', 6), ('d', 7), ('e', 8)])

 

转载于:https://www.cnblogs.com/deeptester-vv/p/11539786.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值