Skip to content

Instantly share code, notes, and snippets.

View Everfighting's full-sized avatar
😁
I may be slow to respond.

蔡大锅 Everfighting

😁
I may be slow to respond.
View GitHub Profile
from random import randint
data = [randint(-10,10) for _ in range(10)]
results = [x for x in data if x >= 0]
# 列表解析的速度更快,用timeit测试
@Everfighting
Everfighting / list_filter.py
Created May 15, 2017 15:47
筛出字典{‘Lilei’:79,'Jim':88,'Lucy':92}中高于90的项
from random import randint
d = {x: randint(60,100) for x in range(1,21)}
result = {k : v for k, v in d.iteritems() if v > 90}
@Everfighting
Everfighting / set_filter.py
Created May 15, 2017 15:51
集合解析进行筛选
data = [2,-1,-3,6,8,2]
s = set(data)
# s= {2,-1,-3,6,8}
results = {x for x in s for x % 3 == 0}
# {-3,6}
@Everfighting
Everfighting / namedtuple_demo.py
Created May 16, 2017 15:27
元组元素命名,使得下标更有含义
from collections import namedtuple
Student = namedtuple('Student',['name','age','sex','email'])
# 位置传参
s = Student('Jim',16,'male','[email protected]')
# 关键字传参
s2 = Student(name ='Jim', age = 16, sex = 'male', email = '[email protected]')
# 类对象访问元组
s.name
# isinstance(s,tuple)
True
@Everfighting
Everfighting / count_number.py
Created May 16, 2017 15:39
统计序列中元素出现的频度,及最高的三个值
from random import randint
data = [randint(0,20) for _ in range(30)]
c = dict.fromkeys(data,0)
for x in data:
c[x] += 1
@Everfighting
Everfighting / sort_dict.py
Created May 16, 2017 16:11
根据字典的值大小对字典的项排序
from random import randint
{x: ranin(60,100) for x in 'xyzabc'}
# {'a':97,'b':69,'c':78,'x':66,'y':95,'z':72}
sorted(d)
# ['a','b','c','x','y','z']
iter(d)
# dictionary-keyiterator at 0x7f030d0d1f18
list(iter(d))
['a','c','b','y','x','z']
(97,'a') > (69,'b')
>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
@Everfighting
Everfighting / same_key.py
Created May 18, 2017 14:28
如何快速找到多个字典中出现的公共键
from random import randint,sample
s1 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))}
s2 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))}
s3 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))}
# 法一
res = []
for k in s1:
if k in s2 and s3:
res.append(k)
@Everfighting
Everfighting / rank_demo.py
Created May 18, 2017 14:39
如何让字典保持有序
from time import time
from random import ranint
from collections import OrderedDict
d = OrderedDict()
players = list('ABCDEFGH')
start = time()
for i in range(8):
input()
@Everfighting
Everfighting / history_demo.py
Last active May 18, 2017 14:52
实现用户的历史记录功能
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