在np.array python中找到前10个最常出现的元素

时间:2017-12-09 20:56:02

标签: python numpy

我想找到这个np.array中最常出现的元素

[[ 2  8 15 ..., 10  4 16]
 [ 2  7 18 ..., 20 14 21]
 [ 3  4 15 ...,  1 24  6]
  ...,
 [ 8  0 18 ..., 17  3 14]
 [ 3 34 39 ...,  8 35 38]
 [ 8  3 14 ..., 18 10  6]]

1 个答案:

答案 0 :(得分:2)

这应该可以胜任。

public class Main {

    public static void main(String[] args) {

        String[] statement = {"-in", "FILENAME", "-out", "FILENAME", "-keep", "-typ", ".avi", "-status"};
        String[] validArgs = {"-in", "-out", "-keep", "-typ", "-status"};

        ArrayList<CutStatement> cuttedOutputList = new ArrayList<>();


        for (int i = 0; i < statement.length; i++) {
            // do not use Arrays.asList() here. It will create a List instance in each iteration
            // not sure that stream is the best solution though
            int i_temp = i; // for lambda in stream
            boolean contains = true;
            if (i != statement.length - 1) { // if it is not the last element
                contains = Arrays.stream(validArgs).anyMatch(s -> s.equals(statement[i_temp + 1]));
            }
            if (contains) {
                // just do not use `[i]` here
                CutStatement obj = new CutStatement(statement[i]);
                cuttedOutputList.add(obj);
            } else {
                CutStatement obj = new CutStatement(statement[i], statement[i + 1]);
                cuttedOutputList.add(obj);
                i++; // increase i because we added two values from `statement`
            }
        }
        System.out.println(cuttedOutputList);
    }

}

class CutStatement {
    private String argument;
    private String value;
    private boolean hasValue;

    public CutStatement(String argument) {
        this.argument = argument;
        this.hasValue = false;
    }

    public CutStatement(String argument, String value) {
        this.argument = argument;
        this.value = value;
        this.hasValue = true;
    }

    @Override
    public String toString() {
        if (hasValue) {
            return "(" + argument + " = " + value + ")";
        } else {
            return "(" + argument + ")";
        }
    }
}