Comparing Two Arrays Resulting Into Third Array
Solution 1:
First, convert firstArray
into a dict with the country as the key and abbreviation as the value, then just look up the abbreviation for each country in secondArray
using a list comprehension:
abbrevDict = {country: abbrev for abbrev, country in firstArray}
thirdArray = [[key, abbrevDict[country]]for key, country in secondArray]
If you are on a Python version without dict comprehensions (2.6 and below) you can use the following to create abbrevDict
:
abbrevDict = dict((country, abbrev) for abbrev, country in firstArray)
Or the more concise but less readable:
abbrevDict = dict(map(reversed, firstArray))
Solution 2:
It is better to store them into dictionaries:
firstDictionary = {key:value for value, key in firstArray}
# in older versions of Python:# firstDictionary = dict((key, value) for value, key in firstArray)
then you could get the 3rd array simply by dictionary look-up:
thirdArray = [[value, firstDictionary[key]]for value, key in secondArray]
Solution 3:
You could use an interim dict
as a lookup:
firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
lookup = {snd:fst for fst, snd in firstArray}
thirdArray = [[n, lookup[name]] for n, name in secondArray]
Solution 4:
If a dictionary would do, there is a special purpose Counter dictionary for exactly this use case.
>>> from collections import Counter
>>> Counter(firstArray + secondArray)
Counter({['AF','AFGHANISTAN']: 1 ... })
Note that the arguments are reversed from what you requested, but that's easily remedied.
Solution 5:
The standard way to match data to a key is a dictionary. You can convert firstArray
to a dictionary using dict comprehension.
firstDict = {x: y for (y, x) in firstArray}
You can then iterate over your second array using list comprehension.
[[i[0], firstDict[i[1]]] for i in secondArray]
Post a Comment for "Comparing Two Arrays Resulting Into Third Array"