writing idiomatic python 读书笔记(3)

来源:互联网 发布:淘宝运费险多少钱一单 编辑:程序博客网 时间:2024/05/16 13:52
变量
(1)使用多作业去压缩变量设置相同值
简洁也不影响可读性
x = y = z = 'foo'
(2)避免使用不必要的临时变量
foo = 'Foo'
bar = 'Bar'
(foo, bar) = (bar, foo)
字符串
(1)字符串函数链来处理字符串
但是不要串太多,最好不要超过3个
book_info = ' The Three Musketeers: Alexandre Dumas'
formatted_book_info = book_info.strip().upper().replace(':', ' by')
(2)学会使用''.jion来用List创建字符串
这样的代码不要出现:学会使用内置函数真的很重要。
result_list = ['True', 'False', 'File not found']
result_string = ''
for result in result_list:
result_string += result
好的方式,也是很常用的:
result_list = ['True', 'False', 'File not found']
result_string = ''.join(result_list)
(3)要获取函数的ascii码要用ord函数
而不是傻傻的:
hash_value = 0
character_hash = {
'a': 97,
'b': 98,
'c': 99,
# ...
'y': 121,
'z': 122,
}
for e in some_string:
hash_value += character_hash[e]
python有俩个内置函数chr和ord
chr是ord逆
hash_value = 0
for e in some_string:
hash_value += ord(e)
return hash_value
(4)使用函数来格式化字符串
以前我是第二种方式,以为很不错了,可是新手就是新手==、
def get_formatted_user_info_worst(user):
# Tedious to type and prone to conversion errors
return 'Name: ' + user.name + ', Age: ' + \
str(user.age) + ', Sex: ' + user.sex
def get_formatted_user_info_slightly_better(user):
# No visible connection between the format string placeholders
# and values to use. Also, why do I have to know the type?
# Don't these types all have __str__ functions?
return 'Name: %s, Age: %i, Sex: %c' % (
user.name, user.age, user.sex)
看到前辈们都是这么写的,我才慢慢改。。。
def get_formatted_user_info(user):
# Clear and concise. At a glance I can tell exactly what
# the output should be. Note: this string could be returned
# directly, but the string itself is too long to fit on the
# page.
output = 'Name: {user.name}, Age: {user.age}, Sex: {user.sex}'.format(user=user)
return output
List
(1)使用列表推导式
创建或者更改列表的时候,是用推倒时,简化代码和提高代码性能
some_other_list = range(10)
some_list = list()
for element in some_other_list:
if is_prime(element):
some_list.append(element + 5)
看起来也没什么问题,但是和这个对比一下,就发现有需要优化的地方
some_other_list = range(10)
some_list = [element + 5
for element in some_other_list
if is_prime(element)]
(2)利用负索引
也就是切片使用的时候,利用负数可以简化很多操作
def get_suffix(word):
return word[-2:]
有过一次面试让翻转字符串的。当时没想起来,
a = 'abcdefg'
a[::-1]
(3)使用列表推导式来代替内置的map()和filter()函数
map()和filter()都是python的过去遗留的问题,现在可以用list来替换掉,list的可读性更高
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_odd(number):
return number % 2 == 1
odd_numbers = filter(is_odd, the_list)
odd_numbers_times_two = list(map(lambda x: x * 2, odd_numbers))
使用list:
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers_times_two = [n * 2 for n in the_list if n % 2 == 1]
(4)使用内置函数去计算
刚接触的新手可能会去自己写函数去解决计算的问题,最好还是用python已经提供的函数,这样达到了使用python来编程的目的。方便快捷
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
the_sum = 0
for element in the_list:
the_sum += element
上面是c语言小伙伴的代码吧。
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
the_sum = sum(the_list)
(5)使用all函数去判断list中所有的函数是否为true
看到这之前我写的代码是这样:
def contains_zero(iterable):
for e in iterable:
if e == 0:
return True
return False
到还真是这样。。。
def contains_zero(iterable):
# 0 is "Falsy," so this works
return not all(iterable)
(6)尽量使用xrange而不是range 除非你要保存你结果列表
why?因为xrange 不会把数字列表保存在内存中,当数据很大的时候,使用xrange代替range可以使性能有很大提升。
# A loop over a large range that breaks out
# early: a double whammy!
even_number = int()
for index in range (1000000):
if index % 2 == 0:
even_number = index
break
百万级的列表,对内存的负担太大。
even_number = int()
for index in xrange(1000000):
if index % 2 == 0:
even_number = index
break






0 0
原创粉丝点击