I have a set of initial variables from a->i, a full list of variables, a separate list of integer values and a set of lists made from subsets of the initial variables:
a=0
b=0
...
i=0
exampleSubList_1 = [c, e, g]
fullList = [a, b, c, d, e, f, g, h, i] #The order of the list is important
otherList = [2, 4, 6, 8, 10, 12, 14, 16, 18] #The order of the list is important
I want my program to read an input exampleList_X and find its corresponding index entry in fullList, and use that index number to output the corresponding value in otherList. For example...
exampleList_1[0]
#Which is c
#It should find index 2 in fullList
#Entry 2 in otherList is the value 6.
#So it should output
6
Is this possible? I would be willing to use tuples/dictionary is required.
In the interest of clarity, this is for a Raspberry Pi noughts and crosses game project using LEDs. c, e and g correspond to the win condition of the diagonal from top right to bottom left, and otherList corresponds to the pin on the Raspberry Pi which sends out a current to light up the LED.
4 Answers 4
List comprehension:
results = [otherList[fullList.index(c)] for c in exampleSubList_1]
and results will return:
[6, 10, 14]
Or a simple for loop:
for c in exampleSubList_1:
print otherList[fullList.index(c)]
Should print
6
10
14
1 Comment
>>> symbol_pos_map = {v:k for k,v in enumerate(fullList)}
>>> otherList[symbol_pos_map[exampleSubList_1[0]]]
6
Don't use list.index, because it does a linear search everytime, first map fullList to a dictionary at linear cost, then subsequent lookups are a constant time.
1 Comment
You really should consider using a dictionary.
Consider:
l1 = ['c', 'e', 'g']
l2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
l3 = [2, 4, 6, 8, 10, 12, 14, 16, 18]
results = [l3[l2.index(c)] for c in l1]
print "results 1:", results
d1 = {'a': 2, 'b': 4, 'c': 6, 'd':8, 'e': 10, 'f': 12, 'g': 14, 'h': 16, 'i': 18}
results = [d1[c] for c in l1]
print "results 2:", results
Those give you the same results. Let the dictionary do what it was designed to do: lookup a key, and return a value.
Note that the key value can be almost anything: a number, a letter, a full string, a tuple of values...
If you already have your two "lookup lists" (l2 and l3 in my example), then you can use the dict() and zip() functions to create the dictionary for you:
d2 = dict(zip(l2, l3)) # this creates a dictionary identical to d1
results = [d2[c] for c in l1]
print "results 3:", results
2 Comments
After reading around dictionaries, I've found that using OrderedDict works perfectly for what I need, see Python select ith element in OrderedDict.
@Dietrich thanks for the idea.
from collections import OrderedDict? ``exampleSubList_1is[0,0,0], sofullList.index(exampleSubList_1[0]) == 0since all your variablesathroughiare0, so there's no telling them apart. Do you meanexampleSubList_1 = ['c','e','g'],fullList = ['a','b','c', ... , 'i']?