<a href="http://www.jianshu.com/p/54870e9541fc">总目录</a>
课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾
dictionary.items()
d = {
"Name": "Guido",
"Age": 56,
"BDFL": True
}
print d.items()
Output:
[('BDFL', True), ('Age', 56), ('Name', 'Guido')]
dict.keys(), dict.values()
Whereas items() returns an array of tuples with each tuple consisting of a key/value pair from the dictionary:
- The keys() function returns an array of the dictionary's keys, and
- The values() function returns an array of the dictionary's values.
d = {
"Name": "Guido",
"Age": 56,
"BDFL": True
}
print d.keys()
print d.values()
Output:
['BDFL', 'Age', 'Name']
[True, 56, 'Guido']
The 'in' operator
# in and string
for char in "in_operator":
print char,
# in and list
for num in range(7):
print num,
# in and dict
d = {
"Name": "Guido",
"Age": 56,
"BDFL": True
}
for dict_key in d:
print dict_key,
Output:
i n _ o p e r a t o r 0 1 2 3 4 5 6 BDFL Age Name
List comprehension: for/in + if
range()可以很快生成lists
But what if we wanted to generate a list according to some logic—for example, a list of all the even numbers from 0 to 50?
list_name = [variable(可编辑)/string for variable in ... if variable ...]
【例1:输出0-50之间的偶数】
even_num = [i for i in range(51) if i % 2 == 0]
print even_num
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
【例2:输出0-50之间的偶数的平方】
even_num = [i**2 for i in range(51) if i % 2 == 0]
print even_num
Output:
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304, 2500]
【例3:输出0-50之间的偶数个"c"】
even_num = ["c" for i in range(51) if i % 2 == 0]
print even_num
Output:
['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
List slicing syntax
list[start:stop:step]
【例1】
list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print list[2:8:1]
print list[2:8:2]
print list[2::2]
print list[:2]
print list[::2]
print list[::-1]
print list[1::-1]
print list[8:1:-1]
Output:
[2, 3, 4, 5, 6, 7]
[2, 4, 6]
[2, 4, 6, 8]
[0, 1]
[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[1, 0]
[8, 7, 6, 5, 4, 3, 2]
Anonymous Functions
【例1:把1-15中3的倍数找出来并打印,只能用一行代码】
print filter(lambda x: x % 3 == 0, range(16))
Output:
[0, 3, 6, 9, 12, 15]
Iterating Over Dictionaries
movies = {
"Monty Python and the Holy Grail": "Great",
"Monty Python's Life of Brian": "Good",
"Monty Python's Meaning of Life": "Okay"
}
#方法一 两种方法结果不同
for key in movies.keys():
print key, movies[key]
#方法二
print movies.items()
Output:
Monty Python's Life of Brian Good
Monty Python's Meaning of Life Okay
Monty Python and the Holy Grail Great
[("Monty Python's Life of Brian", 'Good'), ("Monty Python's Meaning of Life", 'Okay'), ('Monty Python and the Holy Grail', 'Great')]