在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.结构字符串你会经常需求打印字符串。要是有很多变量,防止下面这样: 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) 2.返回tuple元组
def binary(): return 0, 1 result = binary() zero = result[0] one = result[1] 这是没必要的,你完整能够换成这样: def binary(): return 0, 1 zero, one = binary() 要是你需求一切的元素被返回,用个下划线 zero, _ = binary() 就是这么高效率! 3.访问Dict字典你也会经常给 假如你试图访问一个不存在的于 countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: if i in countr: countr[i] += 1 else: countr[i] = 1 for i in range(10): if i in countr: print("Count of {}: {}".format(i, countr[i])) else: print("Count of {}: {}".format(i, 0)) 但是,用 countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: countr[i] = countr.get(i, 0) + 1 for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0))) 当然你也能够用 这还用一个更简单却多费点开支的方法: 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))) 我们也能够用 countr = {num: bag.count(num) for num in bag} 这两种办法开支大是由于它们在每次 4.运用库现有的库只需导入你就能够做你真正想做的了。 还是说前面的例子,我们建一个函数来数一个数字在列表中呈现的次数。那么,曾经有一个库就能够做这样的事情。 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[i])) 一些用库的理由:
最后,它都曾经在那儿了,你不用再造轮子了。 5.在列表中切片/步进
|
请发表评论