Python高效编程(一)

实际编程和面试都会遇到的典型问题。

图片来源于网络

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

from random import randint
from timeit import timeit
​
data = [randint(-10,10) for _ in range(10)]
 
filter(lambda x:x >= 0,data)
#首选列表解析 时间比filter少一半左右
[x for x in data if x >= 0]
​
data = {x:randint(60,100) for x in range(1,21)}
{k:v for k,v in data.items() if v > 90}
​
data = set(data)
{x for x in data if x%3==0}

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

#第一种
# NAME = 0
# AGE = 1
# SEX = 2
# EMAIL = 3
NAME,AGE,SEX,EMAIL = range(4)

student = ('Jan',14,'male','jan@jan.net')

#name
print(student[NAME])

#第二种
from collections import namedtuple

Student = namedtuple('Student',['name','age','sex','email'])
student= Student('Jan',14,'male','jan@jan.net')
#name
print(student[NAME])
student.age
isinstance(student,tuple)

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

from random import randint

data = [randint(1,10) for x in range(20)]
c = dict.fromkeys(data,0)

#第一种
for x in data:
    c[x]+=1
    
#第二种
from collections import Counter

c2 = Counter(data)
#出现频度最高的三个
c2.most_common(3)

#统计一篇文章中单词出现次数
import re
#导入Python之禅
import this

c3 = Counter(re.split('\W+',this.s))

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

from random import randint

data = {x:randint(60,100) for x in 'abcdefg'}
#sorted(data.values())

#第一种
t = zip(data.values(),data.keys())
sorted(t)

#第二种
sorted(data.items(),key=lambda x: x[1])

如何快速找到多个字典中的公共键(key)

from random import randint,sample

s1 = {x: randint(1,4) for x in sample('abcdefgh',randint(3,6))}
s2 = {x: randint(1,4) for x in sample('abcdefgh',randint(3,6))}
s3 = {x: randint(1,4) for x in sample('abcdefgh',randint(3,6))}

#第一种
res = []
for k in s1:
    if k in s2 and k in s3:
        res.append(k)
        
#第二种
from functools import reduce

s1.keys()&s2.keys()&s3.keys()
map(dict.keys,[s1,s2,s3])
reduce(lambda a, b:a & b,map(dict.keys,[s1,s2,s3]))

如何让字典保持有序

d = {}

d['Tom'] = (1,30)
d['Linda'] = (1,40)
d['Jack'] = (1,50)

from collections import OrderedDict

d = OrderedDict()
d['Tom'] = (1,30)
d['Linda'] = (1,40)
d['Jack'] = (1,50)
d.keys()

from time import time
from random import randint

sorce = OrderedDict()
players = list('abcdefgh')
start = time()

for i in range(8):
    input()
    p = players.pop(randint(0, 7 - i))
    end = time()
    print(i+1,p,end - start)
    sorce[p] = (i+1,end - start)
print('-'*20)

for k in sorce:
    print(k,sorce[k])

如何实现用户的历史记录功能(最多n条)

from collections import deque
from random import randint

N = randint(0,100)
# 一个容纳5个值的队列
history = deque([],5)

def guess(k):
    if k == N:
        print('right!')
        return True
    if k < N:
        print('%s is less than N'%k)
    else:
        print('%s is greater than N'%k)
    return False

while True:
    input_number = input('please input a number: ')
    if input_number.isdigit():
        k = int(input_number)
        history.append(k)
        if guess(k):
            break
    elif input_number == 'history':
        print(list(history))

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏张善友的专栏

LINQ via C# 系列文章

LINQ via C# Recently I am giving a series of talk on LINQ. the name “LINQ via C...

2635
来自专栏落花落雨不落叶

canvas画简单电路图

60811
来自专栏一个爱瞎折腾的程序猿

sqlserver使用存储过程跟踪SQL

USE [master] GO /****** Object: StoredProcedure [dbo].[sp_perfworkload_trace_s...

2040
来自专栏一个会写诗的程序员的博客

Spring Reactor 项目核心库Reactor Core

Non-Blocking Reactive Streams Foundation for the JVM both implementing a Reactiv...

2142
来自专栏菩提树下的杨过

Flash/Flex学习笔记(23):运动学原理

先写一个公用的小球类Ball: package{ import flash.display.Sprite; //小球 类 public class B...

25210
来自专栏陈仁松博客

ASP.NET Core 'Microsoft.Win32.Registry' 错误修复

今天在发布Asp.net Core应用到Azure的时候出现错误InvalidOperationException: Cannot find compilati...

4838
来自专栏hbbliyong

WPF Trigger for IsSelected in a DataTemplate for ListBox items

<DataTemplate DataType="{x:Type vm:HeaderSlugViewModel}"> <vw:HeaderSlug...

4064
来自专栏pangguoming

Spring Boot集成JasperReports生成PDF文档

由于工作需要,要实现后端根据模板动态填充数据生成PDF文档,通过技术选型,使用Ireport5.6来设计模板,结合JasperReports5.6工具库来调用渲...

1.2K7
来自专栏转载gongluck的CSDN博客

cocos2dx 打灰机

#include "GamePlane.h" #include "PlaneSprite.h" #include "BulletNode.h" #include...

5406
来自专栏张善友的专栏

Mix 10 上的asp.net mvc 2的相关Session

Beyond File | New Company: From Cheesy Sample to Social Platform Scott Hansel...

2547

扫码关注云+社区