Python基础知识--Slice(切片)和Comprehensions(生成式)
最近在Youtube的Python视频教程上学习Python相关的基础知识,视频由Corey Schafer制作,讲得十分简单明了,英文发音也比较清晰,几乎都能听懂,是一个不错的Python入门学习的视频,同时还能学学英语。本篇博客用代码记录一下所学的相关基础知识,虽然很简单,但是自己再写一遍加深印象。
Slicing Lists and Strings(切片)
切片用来操作list和string类型,以下几个例子差不多可以掌握切片了。
# 语法 list[start:end:step]
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# -10,-9,-8,-7,-6,-5,-4,-3,-2,-1
print my_list[1:5]
# result : [1, 2, 3, 4]
print my_list[-7:-2]
# result : [3, 4, 5, 6, 7]
print my_list[:]
# result : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#间隔为2
print my_list[1:8:2]
# result : [1, 3, 5, 7]
#反转list
print my_list[::-1]
# result : [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
#String同样可以用切片
sample = "hello world"
print sample[::-1]
# result : dlrow olleh
Comprehensions (生成式)
生成式可以用十分简洁的语言生成多种list。
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list = []
# 01---I want 'n*n' for each 'n' in nums
# 传统方式
# for n in nums:
# my_list.append(n)
# 生成式
my_list = [n*n for n in nums]
print my_list
# result : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 02---I want 'n' for each 'n' in nums if 'n' is even
# 传统方式
#for n in nums:
# if n%2 == 0:
# my_list.append(n)
# 生成式
my_list = [n for n in nums if n%2==0]
print my_list
# result : [2, 4, 6, 8, 10]
# 03--- I want a (letter, num) pair for each letter in "abc" and each num in "012"
#传统方式
#for letter in 'abc':
# for num in range(3)
# my_list.append((letter,num))
# 生成式
my_list = [(letter, num) for letter in 'abc' for num in range(3)]
print my_list
# result :[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2), ('c', 0), ('c', 1), ('c', 2)]
# Dictionary Comprehensions
names = ['Bruce', 'Clark', 'Peter']
heros = ['Batman', 'Superman', 'Spiderman']
# I want a dict{'name':'hero'} for each name, hero in zip(name, heros)
# 传统方式
my_dict = {}
#for name, hero in zip(names, heros):
# my_dict[name] = hero
# 生成式 注意为大括号
my_dict = {name: hero for name, hero in zip(names, heros)}
print my_dict
# result : {'Bruce': 'Batman', 'Peter': 'Spiderman', 'Clark': 'Superman'}
# Set Comprehensions
nums = [1, 1, 2, 3, 3, 4, 5 ]
# 生成式 注意为大括号
my_set = {n for n in nums}
print my_set
# result set([1, 2, 3, 4, 5])