下面是十个Python中很有用的贴士和技巧。其中一些是初学这门语言常常会犯的错误。 注意:假设我们都用的是Python 3 1. 列表推导式你有一个list:bag = [1, 2, 3, 4, 5] 现在你想让所有元素翻倍,让它看起来是这个样子:[2, 4, 6, 8, 10] 大多初学者,根据之前语言的经验会大概这样来做 [size=0.85em]bag = [1, 2, 3, 4, 5] for i in range(len(bag)): bag = bag * 2 但是有更好的方法: [size=0.85em]bag = [elem * 2 for elem in bag] 很简洁对不对?这叫做Python的列表推导式。 2. 遍历列表还是上面的列表。如果可能尽量避免这样做: [size=0.85em]bag = [1, 2, 3, 4, 5] for i in range(len(bag)): print(bag) 取而代之的应该是这样: [size=0.85em]bag = [1, 2, 3, 4, 5] for i in bag: print(i) 如果x是一个列表,你可以对它的元素进行迭代。多数情况下你不需要各元素的索引,但如果你非要这样做,那就用enumerate函数。它像下边的样子: [size=0.85em]bag = [1, 2, 3, 4, 5] for index, element in enumerate(bag): print(index, element) 非常直观明了。 3. 元素互换如果你是从java或者C语言转到Python来,可能会习惯于这样: [size=0.85em]a = 5 b = 10 # 交换 a 和 b tmp = a a = b b = tmp 但Python提供了一个更自然更好的方法! [size=0.85em]a = 5 4. 初始化列表b = 10 # 交换a 和 b a, b = b, a 假如你要一个是10个整数0的列表,你可能首先想到: [size=0.85em]bag = [] for _ in range(10): bag.append(0) 换个方式吧: [size=0.85em]bag = [0] * 10 看,多优雅。 注意:如果你列表包含了列表,这样做会产生浅拷贝。 举个例子: [size=0.85em]bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0], [0]] bag_of_bags[0][0] = 1 # [[1], [1], [1], [1], [1]] Oops!所有的列表都改变了,而我们只是想要改变第一个列表。 改一改啦: [size=0.85em]bag_of_bags = [[0] for _ in range(5)] # [[0], [0], [0], [0], [0]] bag_of_bags[0][0] = 1 # [[1], [0], [0], [0], [0]] 5. 构造字符串 你会经常需要打印字符串。要是有很多变量,避免下面这样: [size=0.85em]name = "Raymond" age = 22 born_in = "Oakland, CA" string = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "." print(string) 额,这看起来多乱呀?你可以用个漂亮简洁的方法来代替,.format。 这样做: [size=0.85em]name = "Raymond" 6. 返回tuples(元组)age = 22 born_in = "Oakland, CA" string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in) print(string) Python允许你在一个函数中返回多个元素,这让生活更简单。但是在解包元组的时候出出线这样的常见错误: [size=0.85em]def binary(): return 0, 1 result = binary() zero = result[0] one = result[1] 这是没必要的,你完全可以换成这样: [size=0.85em]def binary(): return 0, 1 zero, one = binary() 要是你需要所有的元素被返回,用个下划线_: [size=0.85em]zero, _ = binary() 就是这么高效率! 7. 访问Dicts(字典)你也会经常给dicts中写入key,value(键,值)。 如果你试图访问一个不存在的于dict的key,可能会为了避免KeyError错误,你会倾向于这样做: [size=0.85em]countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: if i in countr: countr += 1 else: countr = 1 for i in range(10): if i in countr: print("Count of {}: {}".format(i, countr)) else: print("Count of {}: {}".format(i, 0)) 但是,用get()是个更好的办法。 [size=0.85em]countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: countr = countr.get(i, 0) + 1 for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0))) 当然你也可以用setdefault来代替。 这还用一个更简单却多费点开销的办法: [size=0.85em]bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] countr = dict([(num, bag.count(num)) for num in bag]) for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0))) 你也可以用dict推导式。 [size=0.85em]countr = {num: bag.count(num) for num in bag} 这两种方法开销大是因为它们在每次count被调用时都会对列表遍历。 8 使用库现有的库只需导入你就可以做你真正想做的了。 还是说前面的例子,我们建一个函数来数一个数字在列表中出现的次数。那么,已经有一个库就可以做这样的事情。 [size=0.85em]from collections import Counter bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] countr = Counter(bag) for i in range(10): print("Count of {}: {}".format(i, countr)) 一些用库的理由:
你可以指定start的点和stop点,就像这样list[start:stop:step]。我们取出列表中的前5个元素: [size=0.85em]bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[:5]: print(elem) 这就是切片,我们指定stop点是5,再停止前就会从列表中取出5个元素。 要是最后5个元素怎么做? [size=0.85em]bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[-5:]: print(elem) 没看明白吗?-5意味着从列表的结尾取出5个元素。 如果你想对列表中元素间隔操作,你可能会这样做: [size=0.85em]bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for index, elem in enumerate(bag): if index % 2 == 0: print(elem) 但是你应该这样来做: [size=0.85em]bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[::2]: print(elem) # 或者用 ranges bag = list(range(0,10,2)) print(bag) 这就是列表中的步进。list[::2]意思是遍历列表同时两步取出一个元素。 你可以用list[::-1]很酷的翻转列表。 10. tab键还是空格键长时间来看,将tab和空格混在一起会带来很多不必要的麻烦,你会看到IndentationError: unexpected indent。不管你选择tab键还是空格键,你应该在你的文件和项目中一直保持使用。 一个使用空格而不是tab的原因是,tab不是在所有编辑器中都一样的。视呢所用的编辑器,tab可能会被当作2到8个空格。 你也可以在写代码时用空格来定义tab。这样你可以自己选择用几个空格来当做tab。大多数Python用户是用4个空格。 ![]() |

|免责声明|本站介绍|工控课堂
( 沪ICP备14007696号-3 )|网站地图
GMT+8, 2019-3-21 23:27 , Processed in 0.034207 second(s), 30 queries .
Powered by Discuz! X3.4
© 2001-2017 Comsenz Inc.