Python_7_Codecademy_7_Lists, For

2016-04-17  本文已影响22人  张一闻

<a href="http://www.jianshu.com/p/54870e9541fc">总目录</a>


课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾

Lists

list_sample = [1, 2, 3, "ZHANG Yong", "张雍"]
list_sample.insert(1, 1.5)
# 就变成了:[1, 1.5, 2, 3, "ZHANG Yong", "张雍"]
#sort list_A in alphabetical order
list_A = ["cool", "astronaut", "zebra", "xenophobia", "recursive"]
list_A.sort()
print list_A

Output:
['astronaut', 'cool', 'recursive', 'xenophobia', 'zebra']

list_A = ["cool", "astronaut", "zebra", "xenophobia", "recursive"]
list_A.remove("cool")
print list_A

Output:
['astronaut', 'zebra', 'xenophobia', 'recursive']

For loop

例0:String Looping
string也是可以loop的:

for x in "ZHANG_Yong"
    print x

Output:
Z
H
A
N
G
_
Y
o
n
g
Process finished with exit code 0

例1:打印出列表中都有哪些items:

list_sample = [1, 2, 3, "ZHANG Yong", "张雍"]
for x in list_sample:
  print "%s is in this list" % x

Output:
1 is in this list
2 is in this list
3 is in this list
ZHANG Yong is in this list
张雍 is in this list

例2:listA是数字,输出其平方,且按照大小排序:

listA = [6, 7, 1, 9, 0]
listB = []
for x in listA:
  listB.append(x**2)
listB.sort()
print listB

Output:
[0, 1, 36, 49, 81]

例3:多个lists作为arguments

list_A = [3, 9, 17, 15, 19]
list_B = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_A, list_B):
    print max(a, b)
Console:
3
9
17
15
30

Dictionaries

d = {"birthday_day" : "1st", "birthday_month" : "June"}
print d["birthday_day"]

Output:
1st

d = {"birthday_day" : "1st", "birthday_month" : "June"}
d["fav_fruit"] = "orange"
print d

Output:
{'birthday_month': 'June', 'birthday_day': '1st', 'fav_fruit': 'orange'}

d = {"birthday_day" : "1st", "birthday_month" : "June"}
d["fav_fruit"] = ["orange", "avocado", "banana"]
print d

Output:
{'birthday_month': 'June', 'birthday_day': '1st', 'fav_fruit': ['orange', 'avocado', 'banana']}

d = {
    'birthday_month': 'June', 
    'birthday_day': '1st', 
    'fav_fruit': ['orange', 'avocado', 'banana']
}
# grab my first two fav food
d = {
    'birthday_month': 'June', 
    'birthday_day': '1st', 
    'fav_fruit': ['orange', 'avocado', 'banana']
}
print d["fav_fruit"][:2]

Output:
['orange', 'avocado']

d = {
    'fav_fruit': ['orange', 'avocado', 'banana'],
    'birthday_month': 'June', 
    'birthday_day': '1st', 
}
# 注意上面dictionary里面tuples的顺序
for x in d:
    print x + ":", d[x] 

Output:
birthday_month: June
birthday_day: 1st
fav_fruit: ['orange', 'avocado', 'banana']
注意这里的顺序

上一篇下一篇

猜你喜欢

热点阅读