Cross-reference lists in Python
I'm trying to make a function that takes an input, compares that input to a list of lists, and returns an item from another list with the same number of objects.
Example:
list_1=[[1,2,3],[4,5],[6,7,8]]
list_2=['a','b','c']
-
If
input
- 1, 2 or 3 the function returns'a'
-
If
input
is 4 or 5 the function returns'b'
-
If
input
- 6, 7 or 8 the function returns'c'
I am new to python and have been thinking about the problem for a while and looking at the clues with no results. Any advice / hints that can help me figure this out would be appreciated! Thank!
source to share
You can loop through each list in list_1
and check if the input is in one. If so, you can print the appropriate index list_2
(assuming it is composed of only single values) that you get using an enum in a loop.
input = 1
for idx,i in enumerate(list_1):
if input in i:
return list_2[idx]
In this case, I returned 'a'
.
source to share
zip is a function that "zips together".
It will generate pairs from each list:
>>> combined = zip(list_1, list_2)
[([1, 2, 3], 'a'), ([4, 5], 'b'), ([6, 7, 8], 'c')]
>>> test_key = 5
>>> for keys, value in combined:
... if test_key in keys:
... print value
'b'
Additional preprocessing will allow you to look directly at the value. For example, you can write all keys (from the first list) for a given value (from the second list) to dict
.
>>> value_dict = {}
>>> for keys, value in combined:
... for key in keys:
... value_dict[key] = value
>>> value_dict
{1: 'a', 2: 'a', 3: 'a', 4: 'b', 5: 'b', 6: 'c', 7: 'c', 8: 'c'}
>>> value_dict[5]
'b'
>>> value_dict.get(42, "not found")
"not found"
source to share
To be more flexible, you can make a list of alphabets (at least for this example) at the beginning of the function.
def crossRef(inList, inputNum):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
i = 0
for listItem in inList:
if inputNum in listItem:
return alphabet[i]
i += 1
return None
source to share
Function:
def find_list_two_value(value, list_1, list_2):
for i in list_1:
if value in i:
return list_2[list_1.index(i)]
return none
note: you can add some error handling to it. Index error
Testing:
list_1 = [[1,2,3],[4,5],[6,7,8]]
list_2 = ['a','b','c']
print find_list_two_value(6, list_1, list_2)
output: c
Docs: For loop
source to share
This should do what you are looking for:
def crossReferenceInLists(input, list1, list2):
for index, item in enumerate(list1):
if input not in item:
continue
try:
return list2[index]
except IndexError:
return None
return None
print(crossReferenceInLists(2, [[1, 2, 3], [4, 5], [6, 7, 8]], ['a', 'b', 'c']))
print(crossReferenceInLists(7, [[1, 2, 3], [4, 5], [6, 7, 8]], ['a', 'b', 'c']))
$ python so.py
and
from
source to share