我有两个字符串数组,每个数组包含三列。我想比较两个二维数组(具有 3 列和 4000 行)的前两列。如果它们匹配,那么我需要那些匹配值。但我的代码不起作用。这是一个示例。
array1=["1stcolumn...", "2ndColumn...", "3rdColumn..."]
array2=[1stcolumn 2ndColumn 3rdColumn]
if (array1[0]==array2[0] and array1[1]==array2[1]):
array3.append('matches: {!r}'.format(array1))
print(array3)
最佳答案
编辑
if array1[:2] == array2[:2]:
比较从索引 0 到 2 的所有项目(不包括 2),得出与 如果 array1[0] == array2[0] 和 array1[1] == array2[1]:
。而且,它更简单。(感谢 Wyatt 的评论)
如果您的数组是二维的:
def compare_columns(array1, array2):
if len(array1) != len(array2):
return False # If row numbers are not same, return false
for row_number in range(len(array1)):
if array1[row_number][:2] != array2[row_number][:2]:
return False # If the content is not equal, return false
return True # All of the content is equal, the return true
# For example, these are 2-dimensional arrays
array1 = [["1.1", "1.2", "Lord of the Day of Judgment!"],
["2.1", "2.2", "Lord of the Day of Judgment!"]]
array2 = [["1.1", "1.2", "مَالِكِ يَوْمِ الدِّينِ"],
["2.1", "2.2", "مَالِكِ يَوْمِ الدِّينِ"]]
array3 = []
if compare_columns(array1, array2):
array3.append('matches: {!r}'.format(array1))
print(array3)
输出:
["matches: [['1.1', '1.2', 'Lord of the Day of Judgment!'], ['2.1', '2.2', 'Lord of the Day of Judgment!']]"]
编辑前:
如果你的数组是一维的,就不用说column,就是item。然后你的工作就像你上面所做的那样容易。只是,您有一些语法错误。使用此代码:
array1 = ["1stcolumn", "2ndColumn", "1-3rdColumn"]
array2 = ["1stcolumn", "2ndColumn", "2-3rdColumn"]
array3 = []
if array1[0] == array2[0] and array1[1] == array2[1]:
array3.append('matches: {!r}'.format(array1))
print(array3)
输出:
["matches: ['1stcolumn', '2ndColumn', '1-3rdColumn']"]
所以,如果您有任何其他问题,请告诉我们。
关于python - 如何一次将二维数组的两列与python中另一个数组的列进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46867709/