簡體   English   中英

如何從python列表中分離連續和非連續數字

[英]How to separate Consecutive and Non consecutive number from a python list

輸入:lst = [101,102,103,104,120,131,132,133,134]

預期輸出:連續 - [101,102,103,104,131,132,133,134] 非連續 = [120]

def first_consecutive(lst):
    a = []
    for i,j in enumerate(lst,lst[0]):
        if i!=j:
            a.append(j)
    return a

有什么建議嗎?

您可以在遍歷(排序的)數字時保留一個列表。 當您遇到連續的內容時,請將其添加到列表中。 否則,將值放在正確的位置並重新定義列表。 展示比解釋更容易:

l = [101,102,103,104, 120,131,132,133,134]

def partition_groups(l):
    out = [[], []]
    current = [l[0]]
    for n in l[1:]:
        if current[-1] + 1 == n:
            current.append(n)
        else:
            out[len(current) > 1].extend(current)
            current = [n]
    out[len(current) > 1].extend(current)
    return out
            
nonconsecutive, consecutive = partition_groups(l)      

print(nonconsecutive)
# [120]

print(consecutive)
# [101, 102, 103, 104, 131, 132, 133, 134]

這個? (假設列表已經排序,如果不是先調用lst.sort()

(只需將每個元素與其前一個(如果有)和下一個(如果有)鄰居進行比較。)

consec = []
non_consec = []
L = len(lst)
for i in range(L):
    if i>0 and lst[i-1]==lst[i]-1 or i<L-1 and lst[i+1]==lst[i]+1:
        consec.append(lst[i])
    else:
        non_consec.append(lst[i])

你可以做這樣的事情

def sort_list(list):
    sorted_list = []
    non_consecutive_list = []

    for i in range(len(list)):
        if list[i] + 1 in list or list[i] - 1 in list:
           sorted_list.append(list[i])
        
        else:
           non_consecutive_list.append(list[i])

    return sorted_list, non_consecutive_list

num_list = [101,102,103,104,120,131,132,133,134]

sorted_list, non_consecutive_list = sort_list(num_list)
print(sorted_list, non_consecutive_list)

暫無
暫無

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

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