对字典进行排序
(1)升序:
d={"a":1,"d":4,"c":3,"b":2}
print(sorted(d.items()))
或采用下面操作
d={"a":1,"b":2,"c":3}
for k in sorted(d.keys(),reverse=True):
print(str(k),":",d[k])
运行结果:[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
(2)降序:
d={"a":1,"d":4,"c":3,"b":2}
print(sorted(d.items(),reverse=True))
运行结果:[('d', 4), ('c', 3), ('b', 2), ('a', 1)]
print("{:o},{:x},{:b}".format(64,64,64))
运行结果:100,40,1000000
(3)统计字符串中各字符出现的次数。
s=input("inter:")
d=dict()
for ch in s:
d[ch]=d.get(ch,0)+1
d=sorted(d.items(),reverse=True) #按key值降序排序,若升序则可直接用d=sorted(d.items())即可
print(d)
#如输入s的值为:aaabbccddd,则输出为:[('d', 3), ('c', 2), ('b', 2), ('a', 3)]
也可用下面代码:
s=input("inter:")
d=dict()
for ch in s:
d[ch]=d.get(ch,0)+1
print(d) #此时d为字典,若用sorted则变成列表(为二维数组形式)
将二维数组:b = [
[‘水果’, ‘香蕉’],
[‘水果’, ‘苹果’],
[‘水果’, ‘梨子’],
[‘蔬菜’, ‘西兰花’],
[‘蔬菜’, ‘青菜’],
[‘动物’, ‘牛’],
[‘动物’,‘羊’]
]
转化成:{
‘水果’: [‘香蕉’, ‘苹果’, ‘梨子’],
‘蔬菜’: [‘西兰花’, ‘青菜’],
‘动物’: [‘牛’, ‘羊’]
}
b = [
['水果', '香蕉'],
['水果', '苹果'],
['水果', '梨子'],
['蔬菜', '西兰花'],
['蔬菜', '青菜'],
['动物', '牛'],
['动物','羊']
]
m=[]
n=[]
count=0
for i in b:
for j in i:
count=count+1
if count%2==0:
m.append(j)
else:
n.append(j)
dic={}
for x in range(len(n)):
if n[x] in dic:
dic[n[x]]+=[m[x]]
else:
dic[n[x]]=[m[x]]
print(dic)
递归函数调用深度,一般情况为1000。
>>> import sys
>>> sys.getrecursionlimit()
1000