— 改编自 Python: Tips, Tricks and Idioms
1. Dict的for循环中避免使用低效的iteritems() 和 keys()
In [1]:
a = {}
for i in xrange(0, 1000000):
a[i] = i
print(type(a))
print(len(a))
In [2]:
def for_func1():
for x in a:
pass
def for_func2():
for x in a.keys():
pass
def for_func3():
for x,v in a.iteritems():
pass
In [3]:
import timeit
print(timeit.timeit(for_func1, number=100))
print(timeit.timeit(for_func2, number=100))
print(timeit.timeit(for_func3, number=100))
是不是快多了?
2. for循环中获得index神器: enumerate
In [4]:
students = ('James', 'Andrew', 'Mark')
In [5]:
for i, student in enumerate(students):
print i, student
In [6]:
students = {'James': 'male', 'Andrew':'male', 'Alice':'female'}
In [7]:
for i, student in enumerate(students):
print i, student
3. 想确定for循环完整结束, 用else吧…
In [8]:
for ele in ['a', 'b', 'c']:
if ele == 'b':
break
else: # no break
print('for循环完整结束')
In [9]:
for ele in ['a', 'b', 'c']:
if ele == 'd':
break
else: # no break
print('for循环完整结束')
4. 迭代工具之chain连接器
In [10]:
import itertools
#把所有元素放到一个list中
a=[[1],[2],[3,4],[5,6],[7,8,9]]
print list(itertools.chain(*a))
In [11]:
#甚至还能连接不同类型数据dict和list
b=[{'a': 1, 'b': 2},[2],[3,4],[5,6],[7,8,9]]
print list(itertools.chain(*b))
5. 迭代工具之排列组合
In [12]:
print list(itertools.permutations([1,2,3]))
In [13]:
print list(itertools.combinations([0,1,2,3], 3))
6. zip拉链函数
In [14]:
random_numbers = [1,2,3]
names = ('James', 'Andrew', 'Mark')
print zip(random_numbers, names)
d = dict(zip(random_numbers, names))
print d
In [15]:
li=[['a','b','c'],['d','e','f']]
print zip(*li)
In [16]:
dots = [(1, 3), (2, 4), (3, 5)]
print zip(*dots)
7. with语句的保护性
In [17]:
with open('/etc/passwd', 'r')as f:
print f.read()
In [18]:
print(f)
With 语句结束会自动关闭文件!
8. 数据结构之Counter–计数神器
In [19]:
import collections
print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
print collections.Counter({'a':2, 'b':3, 'c':1})
print collections.Counter(a=2, b=3, c=1)
In [20]:
c = collections.Counter()
print 'Initial :', c
c.update('abcdaab')
print 'Sequence:', c
c.update({'a':1, 'd':5})
print 'Dict :', c
In [21]:
c = collections.Counter()
with open('/usr/share/dict/words', 'rt') as f:
for line in f:
c.update(line.rstrip().lower())
print 'Most common:'
for letter, count in c.most_common(3):
print '%s: %7d' % (letter, count)
9. 数据结构之defaultdict–任何数据转成dict的神器
In [22]:
from collections import defaultdict
order = (
('Mark', 'Steak'),
('Andrew', 'Veggie Burger'),
('James', 'Steak'),
('Mark', 'Beer'),
('Andrew', 'Beer'),
('James', 'Wine'),
)
#key已经确定, 返回value是list的工厂
group_order = defaultdict(list)
for name, menu_item in order:
group_order[name].append(menu_item)
print group_order
In [23]:
#key已经确定, 返回value是int的工厂
order_count = defaultdict(int)
for name, menu_item in order:
order_count[menu_item] += 1
print order_count
10. 数据结构之defaultdict–记住插入数据的顺序
In [24]:
from collections import OrderedDict
li_order1=['a','b','c','c']
li_order2=['c','b','a','c']
d1 = OrderedDict()
d2 = OrderedDict()
for x in li_order1:
d1[x] = 1
print d1
In [25]:
for x in li_order2:
d2[x] = 1
print d2
11. 数据结构之namedtuple — 闪电般构造一个类
In [26]:
from collections import namedtuple
#namedtuple is a CLASS
Parts = namedtuple('Parts', 'id_num desc cost amount')
In [27]:
auto_parts = Parts(id_num='1234', desc='Ford Engine',
cost=1200.00, amount=10)
print auto_parts.id_num
In [28]:
auto_parts = ('1234', 'Ford Engine', 1200.00, 10)
print auto_parts[2]
In [29]:
id_num, desc, cost, amount = auto_parts
print id_num
Parts = {'id_num':'1234', 'desc':'Ford Engine',
'cost':1200.00, 'amount':10, 'profit': 10000}
parts = namedtuple('Parts', Parts.keys())(**Parts)
print parts
In [30]:
# define new type
BuildInput = namedtuple('BuildInput', ['name', 'files'])
# test scenarios
b1 = BuildInput('test_build_1', ['file1.txt', 'file2.txt'])
b2 = BuildInput(name='test_build_2', files=['file3.txt', 'file4.txt'])
another_b1 = BuildInput(name='test_build_1', files=['file1.txt', 'file2.txt'])
print b1 != b2
print b1 == another_b1
12. Python中的Getter 和 setter
In [31]:
class Money:
def __init__(self, dollars, cents):
self.total_cents = dollars * 100 + cents
# Getter and setter for dollars...
@property
def dollars(self):
return self.total_cents // 100;
@dollars.setter
def dollars(self, new_dollars):
self.total_cents = 100 * new_dollars + self.cents
# And the getter and setter for cents.
@property
def cents(self):
return self.total_cents % 100;
@cents.setter
def cents(self, new_cents):
self.total_cents = 100 * self.dollars + new_cents
In [32]:
# with the final Money class. High five!
money = Money(27, 12)
message = "I have {:d} dollars and {:d} cents."
print(message.format(money.dollars, money.cents))
# "I have 27 dollars and 12 cents."
money.dollars += 2
money.cents += 20
print(message.format(money.dollars, money.cents))
# "I have 29 dollars and 32 cents."
# This works correctly, too.
money.cents += 112
print(message.format(money.dollars, money.cents))
# "I have 30 dollars and 44 cents."
How to code with no bugs
一行生成器与一行list写法区分
In [33]:
a = (x**2 for x in [1,2,3,4,5])
print(type(a))
for i in a:
print(i)
In [34]:
b = [x**2 for x in [1,2,3,4,5]]
print(b)
The following two tabs change content below.
David 9
邮箱:yanchao727@gmail.com
微信: david9ml
Latest posts by David 9 (see all)
- 修订特征已经变得切实可行, “特征矫正工程”是否会成为潮流? - 27 3 月, 2024
- 量子计算系列#2 : 量子机器学习与量子深度学习补充资料,QML,QeML,QaML - 29 2 月, 2024
- “现象意识”#2:用白盒的视角研究意识和大脑,会是什么景象?微意识,主体感,超心智,意识中层理论 - 16 2 月, 2024