Iterators for Dictionaries
my_dict = {
"name" : "Zhao",
"age" : 13,
"gender" : 'male'
}
print my_dict.items() #.items()实现对字典的遍历,该函数直接键值对形式的元组(tuple),注意是无序的
#[('gender', 'male'), ('age', 13), ('name', 'Zhao')]
print my_dict.keys() #通过字面意思即可理解函数的功能,一个返回key,一个返回value
print my_dict.values() #注意,仍然是无序。。
#['gender', 'age', 'name']
#['male', 13, 'Zhao']
for key in my_dict:
print key, my_dict[key] #对字典使用for each循环的话,返回的是key,所以要用my_dict[key]来获取对应的value
#gender male
#age 13
#name Zhao
List Comprehension (好像叫推导式?)
List comprehensions are a powerful way to generate lists using the for/in and if keywords
even_squares = [x**2 for x in range(1,12) if x % 2 == 0]
# [4, 16, 36, 64, 100]
#语法没啥难的,感觉有点像sql语句中的select xxx from xxx where xxxx...
List Slicing Syntax
l = [i ** 2 for i in range(1, 11)]
print l[2:9:2] #含头不含尾,第三个参数是步长,第一个参数省略意味着从第一个开始取,第二个参数省略即取到最后一个为止
#并且,步长可以为负值,如[ : : -1] 可以实现对列表的逆转
#[9, 25, 49, 81]
Lambdas(牛13哄哄的lambda)
lambda x: x % 3 == 0`
#Is the same as
def by_three(x):
return x % 3 == 0
Only we don't need to actually give the function a name; it does its work and returns a value without one. That's why the function the lambda creates is an anonymous function.
When we pass the lambda to filter, filter uses the lambda to determine what to filter, and the second argument is the list it does the filtering on.两个参数,第一个传入lambda表明需要选出的东西,第二个传入list表示filter操作的对象,代码:
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
#[0, 3, 6, 9, 12, 15]
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python", languages) #- -!! 在那边x==3 x==2的闹了半天一直报错,原来。。。吸取教训
Bitwise Operation
bin() takes an integer as input and returns the binary representation of that integer in a string.You can also represent numbers in base 8 and base 16 using the oct() and hex() functions.
同时,int()函数有另外一个可选的参数,如:
print int("42")
# 42
print int("110", 2) #这里第二个参数表明,以n进制来识别第一个参数
# 6
位运算整体没什么特殊的,剩下的不写了。
posted on
浙公网安备 33010602011771号