1. 求一个数的幂值
def mi(a, b):
c = a
for i in range(b-1):
a = a * c
return a
print(mi(2, 4))
2. 输出斐波那契数列
def feibonaqi(n):
l = []
a = 1
b = 1
for i in range(n):
l.append(a)
l.append(b)
a = b + a
b = a + b
print(l)
feibonaqi(5)
3. 输出特定字典数据
keys = ['name', 'old', 'score']
values = [
['yee', 3, 99], ['rose', 18, 8], ['green', 30, 90]
]
要输出结果:
[{'name': 'yee', 'old': 3, 'score': 99}, {'name': 'rose', 'old': 18, 'score': 8}, {'name': 'green', 'old': 30, 'score': 90}]
错误示范:
keys = ['name', 'old', 'score'] values = [ ['yee', 3, 99], ['rose', 18, 8], ['green', 30, 90] ] l = [] d = {} for value in values: for i in range(len(keys)): d[keys[i]] = value[i] l.append(d) print(l)
错误原因:
列表追加的元素指向的是同一个字典d,若d字典的键值变化也会同步到列表
例如:
cc = [] aa = {'name': 'green', 'old': 30, 'score': 90} cc.append(aa) aa['name'] = 'yee' aa['old'] = 3 aa['score']= 99 cc.append(aa) print(cc)
输出结果是:[{'name': 'yee', 'old': 3, 'score': 99}, {'name': 'yee', 'old': 3, 'score': 99}]