I need to put 3 items in the list.
- state..eg(1,2)
- action...eg..west
- cost....5
list=[(state,action,cost), (state,action,cost).........]
how can i make it in a form of list. For a particular state , action and cost is there. Moreover, if i need only state from the list, i should be able to extract it from the list.same thing goes for action too.
-
2What exactly is your question?Felix Kling– Felix Kling2010年07月15日 06:02:50 +00:00Commented Jul 15, 2010 at 6:02
4 Answers 4
Your wording is pretty obscure. Right now you have a list of tuples (horribly named list, which robs the use of the built-in name from the rest of that scope -- please don't reuse built-in names as your own identifiers... call them alist or mylist, if you can't think of a more meaningful and helpful name!). If you want a list of lists, code:
alist = [[state, action, cost], [state, action, cost], ...]
If you want to transform the list of tuples in a list of lists,
alist = [list(t) for t in alist]
(see why you should never usurp built-in identifiers such as list?!-).
If you want to flatten the list-of-lists (or -of-tuples) into a single list,
aflatlist = [x for t in alist for x in t]
To access e.g. "just the state" (first item), say of the Nth item in the list,
justthestate = alist[N][0]
or, if you've flattened it,
justhestate = aflatlist[N*3 + 0]
(the + 0 is clearly redundant, but it's there to show you what to do for the cost, which would be at + 1, etc).
If you want a list with all states,
allstates = [t[0] for t in alist]
or
allstates = aflatlist[0::3]
I'm sure you could mean something even different from this dozen of possible interpretations of your arcane words, but I'm out of juice by now;-).
2 Comments
I'm not sure I understand the first part of your question ("form of a list"). You can construct the list of tuples in the form you've stated:
mylist = [(1, 'west', 5), (1, 'east', 3), (2, 'west', 6)]
# add another tuple
mylist.append((2, 'east', 7))
To extract only the states or actions (i.e. the first or second item in each tuple), you can use list comprehensions:
states = [item[0] for item in mylist]
actions = [item[1] for item in mylist]
Comments
The code you listed above is a list of tuples - which pretty much matches what you're asking for.
From the example above, list[0][0] returns the state from the first tuple, list[0][1] the action, and list[0][2] the cost.
You can extract the values with something like (state, action, cost)= list[i] too.
Comments
try this
l = [('a',1,2),('b',3,4),('a',4,6), ('a',6,8)]
state = [sl[0] for sl in l]
or for more,
state = [sl[0] for sl in l if 'a' in sl]