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 。
这样做:
name = "Raymond" 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)返回tuple元组
Python允许你在一个函数中返回多个元素,这让生活更简单。但是在解包元组的时候出出线这样的常见错误:
def binary(): return 0, 1result = binary() zero = result[0] one = result[1]这是没必要的,你完全可以换成这样:
def binary(): return 0, 1zero, one = binary()要是你需要所有的元素被返回,用个下划线 _ :
countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: if i in countr: countr += 1 else: countr = 1for i in range(10): if i in countr: print("Count of {}: {}".format(i, countr)) else: print("Count of {}: {}".format(i, 0))但是,用 get() 是个更好的办法。
countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: countr = countr.get(i, 0) + 1for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0)))当然你也可以用 setdefault 来代替。
这还用一个更简单却多费点开销的办法:
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] # {2: 3, 3: 1, 1: 1, 5: 1, 6: 1, 7: 2, 9: 1}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 推导式。
countr = {num: bag.count(num) for num in bag}这两种方法开销大是因为它们在每次 count 被调用时都会对列表遍历。 使用库
现有的库只需导入你就可以做你真正想做的了。
还是说前面的例子,我们建一个函数来数一个数字在列表中出现的次数。那么,已经有一个库就可以做这样的事情。
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))一些用库的理由: