如何在列表,字典,集合中根据条件筛选数据
过滤掉列表中的负数
from random import randint
data = [randint(-10, 10) for _ in xrange(10)] # 创建10个-10到+10的随机数 3 xrange->range
print(data)
data1 = filter(lambda x: x>=0, data)
print(data)
print(data1)
$ python learning.py
[7, -10, 5, 2, -10, 6, -4, -2, 1, -6]
[7, -10, 5, 2, -10, 6, -4, -2, 1, -6]
[7, 5, 2, 6, 1]
data1 = [x for x in data if x >= 0]
print(data)
print(data1)
timeit 列表解析更快都远快于跌代方案
# 迭代
res = []
for x in data:
if x >= 0:
res.append(x)
print res
d = {x: randint(60, 100) for x in xrange(1,21)}
print d
c = {k: v for k, v in d.iteritems() if v > 90}
print c
筛出集合中能被3整除的元素
data = [randint(-10, 10) for _ in xrange(10)] #xrange->range
s = set(data)
r = {x for x in s if x%3 == 0}
print r
如何为元组中的每个元素命名,提升程序可读性?
// C
#define NAME 0
#define AGE 1
enum Student {
NAME,
AGE,
SEX,
}
# ('jim', 16, 'male', 'jim872@mail.com')
# ('liLei', 17, 'male', 'leile@qq.com')
# ('Lucy' 16, 'female', 'lucy123@yahoo.com')
# NAME = 0
# AGE = 1
# SEX = 2
# EMAIL = 3
NAME, AGE, SEX, EMAIL = xrange(4)
student = ('jim', 16, 'male', 'jim872@mail.com')
# name
print student[NAME]
# age
if student[AGE] >= 18:
# ...
# sex
if student[SEX] == 'male':
# ...
# 开销比普通元组大一点点
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
s = Student('jim', 16, 'male', 'jim872@mail.com')
# name
print s.name
# age
print s.age
# sex
print s.sex
r = isinstance(s, tuple)
print r # True
如何统计序列中元素的出现频度
某随机序列中,找到出现次数最高的3个元素,他们出现次数是多少?
from random import randint
data = [randint(0, 20) for _ in xrange(30)]
print data
c = dict.fromkeys(data, 0)
print c
for x in data:
c[x] += 1
print c
from random import randint
data = [randint(0, 20) for _ in xrange(30)]
print data
from collections import Counter
c2 = Counter(data)
print c2
c3 = c2.most_common(3)
print c3
对某英文文章的单词,进行词频统计,找到出现次数最高的10个单词,他们出现次数是多少?
import re
from collections import Counter
txt = open('aaa.txt').read()
print txt
c = re.split('\W+',txt)
print c
c1 = Counter(c)
print c1
c2 = c1.most_common(1)
print c2
如何根据字典值的大小,对字典中的项排序
某班英语成绩以字典形式存储为,根据成绩高低,计算学生排名.
sorted([9, 1, 2, 8, 5])
# 存储空间少一些浪费 itervalues(), iterkeys()
from random import randint
c = {x: randint(60, 100) for x in 'xyzabc'}
print c
c1 = sorted(c)
print c1
c2 = iter(c)
print c2
c3 = list(iter(c))
print c3
c4 = (97, 'a') > (69, 'b')
print c4
c5 = (97, 'b') > (97, 'a')
print c5
c6 = (97, 'a') > (97, 'b')
print c6
c7 = c.keys()
print c7
c8 = c.values()
print c8
c9 = zip(c8, c7)
print c9
c10 = zip(c.itervalues(), c.iterkeys())
print c10
c11 = sorted(c10)
print c11
c12 = c.items()
print c12
c13 = sorted(c.items(), key=lambda x: x[1])
print c13
如何快速找到多个字典中的公共键(key)
西班牙⚽️联赛,每轮球员进球统计,统计出前N轮,每场比赛都有进球的球员
$ s1.view
$ s1.viewkeys?
from random import randint,sample
a = sample('abcdefg', 3)
print a
b = sample('abcdefg', randint(3,6))
print b
s1 = {x:randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
print s1
s2 = {x:randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s3 = {x:randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
print res
c = s1.viewkeys()
print c
r = s1.viewkeys() & s2.viewkeys() & s3.viewkeys()
print r
r1 = map(dict.viewkeys, [s1, s2, s3])
print r1
r2 = reduce(lambda a,b: a&b, r1)
print r2
如何让字典保持有序
某编程竞赛系统,对参赛选手编程解题进行计时,选手完成题目后,把该选手解题用时记录到字典中,以便选手查询成绩,(答题用时越短越优),比赛结束后,需按排名顺序打印选手成绩,如何实现
d = {}
d['Jim'] = (1, 35)
d['leo'] = (2, 37)
d['Bob'] = (3, 40)
for k in d:
print k
from collections import OrderedDict
d1 = OrderedDict()
d1['Jim'] = (1, 35)
d1['leo'] = (2, 37)
d1['Bob'] = (3, 40)
for k in d1:print k
from time import time
from random import randint
from collections import OrderedDict
d = OrderedDict()
players = list('ABCDEFGH')
print players
start = time()
for i in xrange(8):
raw_input()
p = players.pop(randint(0, 7-i))
end = time()
print i + 1, p, end - start
d[p] =(i+1, end-start)
print
print '-' * 20
for k in d:
print k,d[k]
如何实现用户的历史记录功能(最多n条)
制作一个简单的小游戏,添加历史记录功能,显示用户最近才过的数字,如何实现?
from collections import deque
q = deque([], 5)
c = q.append(1)
print q
q.append(2)
q.append(3)
q.append(4)
q.append(5)
print q
q.append(6)
print q
from random import randint
from collections import deque
N = randint(0, 100)
history = deque([],5)
def guess(k):
if k == N:
print 'right'
return True
if k < N:
print '%s is less than N' % k
if k > N:
print '%s is greater than N' % k
while True:
line = raw_input("please input a number:")
if line.isdigit():
k = int(line)
history.append(k)
if guess(k):
break
elif line == 'history' or line == 'h?':
print list(history)
$ pickle.dump?
$ pickle.load?
from collections import deque
import pickle
q = deque([], 5)
c = q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
pickle.dump(q, open('history', 'w'))
q2 = pickle.load(open('history'))
print q2