字典迭代Python
发布时间:2020-12-20 12:27:10 所属栏目:Python 来源:网络整理
导读:我是 Python的新手. 字典有多个值. dc = {1:['2','3'],2:['3'],3:['3','4']} 如果你迭代’dc’,你会发现有三次出现’3′.第一次出现在1:[‘2′,’3’]. 我想迭代dict以便这样做 if first occurrence of '3' occurs: dosomething()else occurrence of '3' af
我是
Python的新手.
字典有多个值. dc = {1:['2','3'],2:['3'],3:['3','4']} 如果你迭代’dc’,你会发现有三次出现’3′.第一次出现在1:[‘2′,’3’]. if first occurrence of '3' occurs: dosomething() else occurrence of '3' afterwards:#i.e. 2nd time,3rd time.... dosomethingelse() 我怎么能用Python做到这一点 谢谢. 解决方法
您还可以保留元素被查看的次数.使用dict,并在每次瞄准时递增:
#!/usr/bin/python dc = {3:['3','4'],1:['2',2:['3']} de={} def do_something(i,k): print "first time for '%s' with key '%s'" % (i,k) def do_somethingelse(i,j,k): print "element '%s' seen %i times. Now with key '%s'" % (i,k) for k in sorted(dc): for i in dc[k]: if i not in de: de[i]=1 do_something(i,k) else: de[i]+=1 do_somethingelse(i,de[i],k) 正如其他人所说,词典与插入或代码列表的顺序不一样.如果这与排序顺序相同,您可以对键进行排序(使用排序(dc))来区分“第一个”和“后续”.根据项目被查看的次数,此方法很容易扩展为“do_somthing”. 输出: first time for '2' with key '1' first time for '3' with key '1' element '3' seen 2 times. Now with key '2' element '3' seen 3 times. Now with key '3' first time for '4' with key '3' 或者: r=[] for k in sorted(dc): print dc[k] if '3' in dc[k]: r.append("'3' number {} with key: {}".format(len(r)+1,k)) 生产: ["'3' number 1 with key: 1","'3' number 2 with key: 2","'3' number 3 with key: 3"] 列表r将按照dc键的顺序排列3个字符串,然后迭代序列r. 如果您只是寻找“第一个”3然后其余的,您可以使用列表理解: >>> l=[i for sub in [dc[k] for k in sorted(dc)] for i in sub if i == '3'] >>> l ['3','3','3'] >>> l[0] '3' >>> l[1:] #all the rest... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |