how to compare 2 columns of a 2d array at a time with columns of another array in python

余生颓废 提交于 2021-01-27 13:05:52

问题


I have two string arrays each with three columns.I want to compare first two columns of both 2-d arrays(having 3 cols and 4000 rows). if they match then i need those matching values.But my code is not working.Here is a sample.

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)

回答1:


EDIT

if array1[:2] == array2[:2]: compares all items from the index 0 to 2(2 is not included), and comes up with the same result as if array1[0] == array2[0] and array1[1] == array2[1]:. Also, it is simpler.(Thanks to Wyatt for comment)

If your arrays are 2-dimensional:

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)

Output:

["matches: [['1.1', '1.2', 'Lord of the Day of Judgment!'], ['2.1', '2.2', 'Lord of the Day of Judgment!']]"]

BEFORE EDIT:

If your array is one dimensionel, you don't need to say column, it is just item. Then your job is easy like you have done above. Just, you have a few syntax errors. Use this code:

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)

Output:

["matches: ['1stcolumn', '2ndColumn', '1-3rdColumn']"]

So, if you have any other problem, let us know.




回答2:


There are a number of errors in this code snippet which will prevent it from even running without errors.

  • Python lists are declared with commas between elements. For example, a declaration of a list of strings could be:

    array1 = ["this", "is", "a", "list"]

    Examples of using lists in Python (3) can be found here.

  • The Python logical 'and' operator is not &. It is and. See this question.

  • In Python, as in most languages, variables must be declared before they can be referenced. In your code, array3 is never declared. You can always declare an empty list like this:

    array3 = []




回答3:


As always we need a sample data set

In [1]: from random import randint

In [2]: a = [[randint(0, 1) for _ in range(3)] for __ in range(10)]

In [3]: b = [[randint(0, 1) for _ in range(3)] for __ in range(10)]

Have a look at it

In [4]: for aa, bb in zip(a, b): print(aa, bb)
[1, 1, 0] [0, 1, 0]
[0, 0, 0] [1, 0, 0]
[1, 1, 0] [1, 1, 0]
[1, 1, 0] [0, 1, 0]
[0, 0, 0] [1, 0, 0]
[0, 0, 0] [1, 0, 1]
[1, 1, 1] [1, 1, 1]
[0, 1, 0] [1, 0, 0]
[1, 0, 1] [1, 0, 1]
[1, 1, 1] [1, 0, 0]

It seems that there are a few candidates... let's see if we can sort out the sub-lists of the first list where the first 2 elements are equal to the corresponding elements of the corresponding sub-list in the second list.

A possible solution involves a list comprehension, using zip to pair corresponding sub-lists and filtering according to our criterium:

In [5]: c = [aa for (aa, bb) in zip(a, b) if aa[:2]==bb[:2]]

where the comparison is done on two slices of the sub-lists, avoiding the use of the logical operator and.

Comparing c with the dump of a and b (see input cell #4)

In [6]: c
Out[6]: [[1, 1, 0], [1, 1, 1], [1, 0, 1]]

In [7]: 

it seems to me that the list comprehension procedure here proposed is correct.



来源:https://stackoverflow.com/questions/46867709/how-to-compare-2-columns-of-a-2d-array-at-a-time-with-columns-of-another-array-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!