比较导致第三阵列的两个阵列

sau*_*ean 1 python

我有两个数组:

firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
Run Code Online (Sandbox Code Playgroud)

所以我只需要一个类似的数组

thirdArray=[[1,'AF'],[3,'AS']]
Run Code Online (Sandbox Code Playgroud)

我试过any(e[1] == firstArray[i][1] for e in secondArray) 它返回我的真假,如果两个数组的第二个元素匹配.但我不知道如何构建第三个数组.

And*_*ark 6

首先,转换firstArray为以国家为关键字和缩写为值的字典,然后secondArray使用列表理解查找每个国家/地区的缩写:

abbrevDict = {country: abbrev for abbrev, country in firstArray}
thirdArray = [[key, abbrevDict[country]] for key, country in secondArray]
Run Code Online (Sandbox Code Playgroud)

如果您使用的是没有dict理解(2.6及以下版本)的Python版本,则可以使用以下命令创建abbrevDict:

abbrevDict = dict((country, abbrev) for abbrev, country in firstArray)
Run Code Online (Sandbox Code Playgroud)

或者更简洁但更不易读:

abbrevDict = dict(map(reversed, firstArray))
Run Code Online (Sandbox Code Playgroud)