I am newbie in Python.
Dictionary has multiple values.
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
If you iterate over 'dc' you find there are three occurrences of '3'. First occurrence is in 1:['2','3']. I would开发者_如何学C like to iterate over dict so that
if first occurrence of '3' occurs:
dosomething()
else occurrence of '3' afterwards:#i.e. 2nd time, 3rd time....
dosomethingelse()
How can I do this in Python
Thank you.
Assuming the values in the dict are the lists:
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()
Edit (update for your comments about finding the first '3' in the list which is the value of a dict item) - this should work:
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()
Most of what you're asking for is pretty straightforward, the only part I can see you having trouble with is determining if the number 3 occurs after the first element.
You can do this with:
list[1:]
For instance:
>>> 3 in [1,2,4,5][1:]
False
>>> 3 in [3,1,2,4][1:]
False
>>> 3 in [1,2,3,4][1:]
True
Here's something that should work:
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
def dosomething(): print 'something'
def dosomethingelse(): print 'something else'
for key,value in dc.items():
if value[0] == '3':
dosomething()
elif '3' in value[1:]:
dosomethingelse()
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
Output:
doing something
doing something else
doing something else
Here's an alternative that doesn't use an if statement to check if the 3 is the first occurrence.
d = {1:['2', '3'], 2:['3'], 3:['3', '4']}
def doSomething():
print('ds')
def doSomethingElse():
print('dse')
for key,value in d.iteritems():
do = doSomething
for item in value:
if item == '3':
do()
do = doSomethingElse
You can also keep a count of the times the element has been seen. Use a dict for this, and increment with each sighting:
#!/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)
As others have said, dictionaries do not have the same order necessarily as the insertion or code listing. You can just sort the keys (with to sorted(dc)
) to distinguish 'first' vs subsequent if this is the same as sort order. This method is easily extended to 'do_somthing' based on how many times the item has been seen.
Output:
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'
Alternatively:
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))
produces:
["'3' number 1 with key: 1", "'3' number 2 with key: 2", "'3' number 3 with key: 3"]
The list r
will have the 3 strings in the order that the keys of dc
are sorted in, then just iterate over the sequence r
.
And if you are just looking for the 'first' 3
then the rest, you can use a list comprehension:
>>> 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...
Assuming the 'first' is as sorted by the dictionary's keys, this works:
>>> dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
>>> [dc[k] for k in sorted(dc) if '3' in dc[k]][0]
['2', '3']
>>> [dc[k] for k in sorted(dc) if '3' in dc[k]][1:]
[['3'], ['3', '4']]
The code snippet below will give you an idea on how to do it. This will work in single thread execution environment.
For more information start at python docs and Dive Into Python
firstInstance = False
for k in mydict.keys():
obj = mydict.get(k)
for i in range(len(obj)):
value = obj[i]
if value == 3 and firstInstance:
doSomething()
firstInstance = True
else:
doSomethingElse()
精彩评论