Python字典迭代
我刚开始学习Python。
字典里面可以有多个值。
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
如果你遍历'dc',你会发现有三个'3'。第一次出现是在1:['2','3']。
我想遍历这个字典,这样可以找到所有的'3'。
if first occurrence of '3' occurs:
dosomething()
else occurrence of '3' afterwards:#i.e. 2nd time, 3rd time....
dosomethingelse()
我该怎么在Python中做到这一点呢?
谢谢你。
7 个回答
3
dict_ = {1:['2', '3'], 2:['3'], 3:['3', '4']}
def dosomething():
print 'doing something'
def dosomethingelse():
print 'doing something else'
three_handler = dosomething
for v in dict_.values():
for three in [x for x in v if x == '3']:
three_handler()
three_handler = dosomethingelse
输出结果:
doing something
doing something else
doing something else
4
假设字典里的值是一些列表:
foundThree = False
for key, val in dc.items():
if '3' in val and not foundThree:
foundThree = True
# doSomething()
elif '3' in val:
# doSomethingElse()
else:
# doAnotherThing()
补充说明(根据你们的评论,关于如何在列表中找到第一个'3',这个是字典项的值) - 这个方法应该可以用:
for key, val in dc.items():
foundThree = False
for n in val:
if n == '3' and not foundThree:
foundThree = True
# doSomething()
elif n == '3':
# doSomethingElse()
else:
# doAnotherThing()
1
你还可以记录这个元素出现的次数。可以用一个字典来实现,每次看到这个元素时就把计数加一:
#!/usr/bin/python
dc = {3:['3', '4'], 1:['2', '3'], 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,j,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)
正如其他人所说,字典里的顺序不一定和你插入的顺序一样。如果你想区分“第一次”和后续的出现,可以对字典的键进行排序(用 sorted(dc)
)。这个方法也很容易扩展,可以根据这个元素出现的次数来做一些事情。
输出结果:
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...