简体   繁体   中英

Distance from smallest to the largest element in lists (inside a list)

I have a list, the_list = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5], [1, 5, 2, 4, 3, 0]] .How do I find out the distance from the smallest element to the largest element in the list.For example, for the first sublist in the_list the index for the smallest element 0 is 2 and the index for the largest element 5 is 5 . Therefore, the distance between the two indices is 3 Thus I get the following output:

3
1
5
0

Edit: For the last output, it is 0 because the list ends there and assume that the list only looks for distance in bound to the right

Try this:

lst = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5], [1, 5, 2, 4, 3, 0]]
[max(s.index(max(s)) - s.index(min(s)), 0) for s in lst]
=> [3, 1, 5, 0]
>>>list(map(lambda x: x.index(max(x)) - x.index(min(x)) if x.index(max(x)) - x.index(min(x)) > 0 else 0 ,l))
[3, 1, 5, 0]

I don't know python very much, but the algorithm could be similar to this (in pseudocode):

Foreach list in the_list do begin 
    Min:=maxint;
    MinPos:=0;
    Max:=0;
    MaxPos:=0;
    For I := 0 to list.length do begin 
        If list[i] > Max then begin
            Max := list[i];
            MaxPos := i;
        End;
        If list[i] < Min then begin
            Min := list[i];
            MinPos := i;
        End;
    End;
    If MinPos  < MaxPos then
        Write MaxPos - MinPos;
    Elsewhere
        Write 0;
End;

(I'm sorry, I wrote this post at the mobile, and I couldn't format correctly the text).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM