Is there any efficient easy way to compare two lists with the same length with Mathematica?

前端 未结 5 883
感情败类
感情败类 2021-02-13 23:41

Given two lists A={a1,a2,a3,...an} and B={b1,b2,b3,...bn}, I would say A>=B if and only if all ai>=bi.

There is

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-14 00:18

    When working with packed arrays and numeric comparator such as >= it would be hard to beat David's Method #1.

    However, for more complicated tests that cannot be converted to simple arithmetic another method is required.

    A good general method, especially for unpacked lists, is to use Inner:

    Inner[test, a, b, And]
    

    This does not make all of the comparisons ahead of time and can therefore be much more efficient in some cases than e.g. And @@ MapThread[test, {a, b}]. This illustrates the difference:

    test = (Print[#, " >= ", #2]; # >= #2) &;
    
    {a, b} = {{1, 2, 3, 4, 5}, {1, 3, 3, 4, 5}};
    
    Inner[test, a, b, And]
    
    1 >= 1
    2 >= 3
    
    False
    
    And @@ MapThread[test, {a, b}]
    
    1 >= 1
    2 >= 3
    3 >= 3
    4 >= 4
    5 >= 5
    
    False
    

    If the arrays are packed and especially if the likelihood that the return is False is high then a loop such as David's Method #2 is a good option. It may be better written:

    Null === Do[If[a[[i]] ~test~ b[[i]], , Return@False], {i, Length@a}]
    
    1 >= 1
    2 >= 3
    
    False
    

提交回复
热议问题