如何使用Python处理多维数组?

How to process multidimension array using Python?

我想处理一个多维数组。

这是我的数组:

DefaultName = ["AB", "BC", "CD"]
DefaultCode = ["1D", "2D", "3D"]

Name = ["AB", "BC", "CD"]
Code = ["11","12", "13"]

从上面的数组中,每个 DefaultName 值属于 DefaultCode 值。例如,

DefaulCode "1D" belongs to DefaultName "AB" and so on.

对于数组 NameCode 也是如此。 Code 的每个值都属于 Name.

Code "11" belongs to Name "AB" and so on.

我的问题是 Code 的长度与 Name 的长度不同。是这样的:

Name = ["AB", "BC", "CD"]
Code = [None ,"12", "13"]

AB的值为none。所以我需要通过映射 Name.

来寻找从 DefaultCode 中空出的 NameCode

在那种情况下,我的期望是,AB 将具有 DefaultCode 中的 Code,即 1D,因为 1D DefaultName 与 Name 相同代码。

我试过了,但我卡在映射哪个名称的空代码以及如何查找 DefaultCode 的部分。

if (len(Name)) == (len(Code)):
    print("There is no empty code")
else:
    print("There is empty code")
    # looking for the Name that does not has code

    # after know which name that without code, then looking for the code from Default Code by mapping the Name

任何人都可以帮助我。我真的很感激你的帮助。太感谢了。 Gbu

如果代码为空,您可以进行字典查找。

例如:

DefaultName = ["AB", "BC", "CD"]
DefaultCode = ["1D", "2D", "3D"]

DefaultCode = dict(zip(DefaultName, DefaultCode)) # --> {'AB': '1D', 'BC': '2D', 'CD': '3D'}

Name = ["AB", "BC", "CD"]
Code = [" ","12", "13"]

res = {n: c if c.strip() else DefaultCode.get(n, "N/A") for n, c in zip(Name, Code)}
print(res)

输出:

{'AB': '1D', 'BC': '12', 'CD': '13'}

上面的答案很正确,但还有另一种更简单的方法。您可以将两个列表压缩成一个元组列表,例如:

Name = ["AB", "BC", "CD"]
Code = ["11","12", "13"]

NewList = zip(Name, Code)

#iterate through list to demonstrate outputs
for i in NewList:
   print(i)

此代码的输出为:

('AB', '11')
('BC', '12')
('CD', '13')

其中列表中的每个元素都是一个元组。与列表的唯一区别是您不能更改其中的值,因此它们是不可变的。