Python循环与dict的使用

Python之for循环

1
2
3
4
L = ['Adam', 'Lisa', 'Bart']
for name in L
print name

Python之多重循环

1
2
3
for x in ['A', 'B', 'C']:
for y in ['1', '2', '3']:
print x + y
输出的是
A1
A2
A3
B1
B2
B3
C1
C2
C3

Python之while循环

利用while循环计算100以内奇数的和。
1
2
3
4
5
6
sum = 0
x = 1
while x<100:
sum=sum+x
x+=2
print sum

Python之dict

(1)、dict的使用
用dict表示“名字”,“成绩”的查找表如下
1
2
3
4
5
d={
'adam':95,
'lisa':85,
'bart':59
}
我们把名字成为key
对应的成绩成为value
dict就是通过key来查找value;
花括号{}表示这是一个dict,然后key:value,写出来即可
len()函数可以计算任意集合的大小
    len(d)
    输出的是 3

(2)、访问dict
    第一种
        print d['adam']
        95
    第二种
        判断是否存在
        if 'paul' in d:
            print d['paul']
    第三种
        print d.get('bart')
        59
        print d.get('paul')
        None

    例如:
1
2
3
4
5
6
7
8
d = {
'Adam': 95,
'Lisa': 85,
'Bart': 59
}
print 'Adam:',d.get('Adam')
print 'Lisa:',d.get('Lisa')
print 'Bart:',d.get('Bart')
    输出的是
    Adam: 95
    Lisa: 85
    Bart: 59
    要注意的是在‘Adam:’的后面一定要有,(逗号)
(3)、 更新dict
    根据Paul的成绩 72 更新下面的dict:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
d = {
95: 'Adam',
85: 'Lisa',
59: 'Bart'
}
``` bash
d = {
95: 'Adam',
85: 'Lisa',
59: 'Bart'
}
d[72]='Paul'
(4)、dict的遍历
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
for key in d:
    print key

    例如:
    用 for 循环遍历如下的dict,打印出 name: score 来。

    d = {
        'Adam': 95,
        'Lisa': 85,
        'Bart': 59
    }
1
2
3
4
5
6
7
d= {
'Adam': 95,
'Lisa': 85,
'Bart': 59
}
for key in d:
print key , ':', d.get(key)
Fork me on GitHub