list=[1,2,3,4,5,6]
for i ,j in enumerate(list)
print(i,j)
enumerate使用很方便,但是不能访问字典
访问字典还是需要用:
dict_name={k:v for k,v in zip(range(1,len(names)+1),names) }
print(dict_name)
for i,j in dict_name.items():
print(str(i) + ':' + j)
如果需要对字典进行排序,可以用sorted():
names = ['bob', 'tom', 'alice', 'jerry', 'wendy', 'smith','we','jerry']
dict_name={k:v for k,v in zip(range(1,len(names)+1),names) }
for i in dict_name.keys():
print(i)
#对 key 按照排序之后的结果输出
for j in sorted(dict_name.keys(),reverse=True):
print(j)
或者:
# 注意: 一般情况下使用sorted()排序,不要使用sort()排序,这是因为:
# sorted()不会改变原始的列表或字典的顺序;
# sort()是原址排序
names = {1:'bob', 7:'tom', 3:'alice', 2:'jerry', 4:'wendy', 6:'smith',8:'we',5:'jerry'}
new_name = sorted(names.items(),key = lambda names:names[0],reverse=True)
print(new_name)
遍历值时:用value:
names = ['bob', 'tom', 'alice', 'jerry', 'wendy', 'smith','we','jerry']
dict_name={k:v for k,v in zip(range(1,len(names)+1),names) }
for i in dict_name.values():
print(i)
#对value 进行输出,去除重复的值
for j in set(dict_name.values()):
print(j)
本文参考:
https://blog.csdn.net/liu_xzhen/article/details/79564455
https://blog.csdn.net/jasonlee_lijiaqi/article/details/79193229
如有侵权,联系Q276257191删除,