簡體   English   中英

列表中最小元素到最大元素的距離(列表內)

[英]Distance from smallest to the largest element in lists (inside 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]]我是如何找出列表中從最小元素到最大元素的距離。例如,對於the_list的第一the_list列表,最小元素的索引為02 ,最大元素5的索引是5 因此,兩個索引之間的距離是3因此我得到以下輸出:

3
1
5
0

編輯:對於最后一個輸出,它為0,因為列表在那里結束並假設列表僅查找綁定到右側的距離

嘗試這個:

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]

我不太了解python,但算法可能與此類似(在偽代碼中):

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;

(對不起,我在手機上寫了這篇文章,我無法正確格式化文本)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM