简体   繁体   中英

Return a value from array if two other values are known - Python3

Probably a basic question for the more experienced python programmers here, but I am looking for a neat way to find the third value in an array of three parameters if two of them are given.

Example:

array1 = [["a1", 22, 3], ["a2", 222, 4]]
array2 = ["a1", 22]

And I want based on the values given in array 2 to get the value 3 as an answer for this example.

Does converting it into a dict of tuples and using it work for you? See below:

>>> array1 = [["a1", 22, 3], ["a2", 222, 4]]
>>> array1_dict = {(a,b):c for a,b,c in array1}
>>> array1_dict[tuple(array2)]
3
>>> 

The other way is ofcourse to loop over all items in array1 and keep checking the conditions.

>>> for each_item in array1:
...     if each_item[0] == array2[0] and each_item[1] == array2[1]:
...             print(f'My required value: {each_item[2]}')
... 
My required value: 3
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM