Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

python - How do I compare the size of the value at a certain index in an array

Let's say I have 3 arrays of type int.

int[] arr1 = {1,3,8};
int[] arr1 = {2,5,3};
int[] arr1 = {3,7,7};

And I would like to compare each index to the other arrays at the same index and print which one is bigger in a descending order.

So the output would be 1 > 2

I couldn't get any further than this.. I was trying to do it with 2 arrays first and then try to scale it, making it dynamic, but I kept running into errors

for (int i = 0; i < arrays.Count; i++)
{
    for (int d = 0; d < _size; d++)
    {
        //array0: index: 0 value: 1
        //array0: index: 1 value: 3
        //array0: index: 2 value: 5
        var value = arrays[i][d];
        var value2 = arrays[i+1][d];

        Console.WriteLine($"array{i}: index:{d} value: {value}");
    }
}

based on any amount of arrays that there are?

question from:https://stackoverflow.com/questions/65916119/how-do-i-compare-the-size-of-the-value-at-a-certain-index-in-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just to show you there are many ways to do it, here is one with tuples:

int[] arr1 = {1,3,8};
int[] arr2 = {2,5,3};
int[] arr3 = {3,7,7};
int[][] arrays = {arr1,arr2,arr3};
int arraySize = arr1.Length;
int nArrays = arrays.Length;
for (int d = 0; d < arraySize; d++)
{
    var list = new List<(int index,int value)>() {};
    for (int i = 0; i < nArrays; i++)
    {
        list.Add((index:i, value:arrays[i][d]));
    }
    list.Sort((i1,i2)=>i2.value.CompareTo(i1.value));
    Console.Out.Write($"Index {d}: ");
    for (int x = 0; x<nArrays-1; x++)
    {
        Console.Out.Write($"{list[x].value} from array {list[x].index} is greater than ");
    }
    Console.WriteLine($"{list[nArrays-1].value} from array {list[nArrays-1].index}");
}

It produces a List of tuples of index and value, then sorts by value and uses the result to output the desired text. It ought to scale to more arrays and values. I tried to find a more elegant way to produce the list, but I haven't found one yet.

It produces this output:

Index 0: 3 from array 2 is greater than 2 from array 1 which is greater than 1 from array 0
Index 1: 7 from array 2 is greater than 5 from array 1 which is greater than 3 from array 0
Index 2: 8 from array 0 is greater than 7 from array 2 which is greater than 3 from array 1

I was also confused about the > sign in the output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...