I have made a dictionary and I put the keys of the dict in a list. My list contains elements like this:
s = [((5, 4), 'South', 1), ((4, 5), 'West', 1)]
I made a dict from this:
child = dict((t[0], t[1]) for t in s)
keys = child.keys()
print keys
The output is : [(4, 5), (5, 4)]
Now I need to put (4,5) and (5,4) into stack. What should I do?
I tried, but when I do pop from the stack it is giving me the 2 elements together.开发者_JAVA百科
like stack.pop() - output is : [(4, 5), (5, 4)]
. I want to pop one by one... (4,5) and then (5,4)
You can use a list as a stack:
stack = list(child.keys())
print stack.pop()
print stack.pop()
Result:
(5, 4) (4, 5)
Important note: the keys of a dictionary are not ordered so if you want the items in a specific order you need to handle that yourself. For example if you want them in normal sorted order you could use sorted
. If you want them to pop off in reverse order from the order they were in s
you could skip the conversion to a dictionary and just go straight from s
to your stack:
stack = [x[0] for x in s]
print stack.pop()
print stack.pop()
Result:
(4, 5) (5, 4)
I think user wants this:
# python
> stack = [(4, 5), (5, 4)]
> stack.pop(0)
(4,5)
> stack.pop(0)
(5,4)
Just a reminder, though, this is not a proper stack. This is a proper stack:
# python
> stack=[]
> stack.append( (4,5) )
> stack.append( (5,4) )
> stack.pop()
(5,4)
> stack.pop()
(4,5)
use
element = stack[0]
if len(stack) > 0:
stack = stack[1:]
print element
but it is not that kind of a stack :/
精彩评论