簡體   English   中英

將刪除其他列表**內部**的每個子列表的函數

[英]function that will remove every sublist that is **inside** of other list

如果我有這個列表列表

[[8,7,5,6,8],[6,4,6,3],[4,6],[8,7,5,6],[7],[6,4,35]]

我該怎么做才能返回這個: [[8,7,5,6,8],[6,4,35]] 我的意思是我想要一個函數來刪除其他列表的每個子列表。

我已經有了可以查看是否發生這種情況的功能

def DNAoccursQ(w1,w2):
if len(w1)==len(w2):
    i=0
    while i<len(w1):
        if w1[i] != w2[i]:
            return False
        i+=1
    return True

elif len(w1)>len(w2):
    return False

else:
    for i in range(len(w2)-1):
        if w2[i] != w1[0]:
            i+=1
        else:
            p=i
            t=0
            for t in range(len(w1)):
                if w1[t] == w2[p]:
                    p += 1
                    t+=1
                elif w1[t]!=w2[p]:
                  return False
            return True
return False

如果您沒有一個龐大的列表,您可以將每個列表與其他列表進行對比:

def is_subsequence(a: list[int], b: list[int]) -> bool:
    """Returns whether b is a subsequence of a."""
    return any(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))


def get_unique_lists(nums: list[list[int]]) -> list[list[int]]:
    """Removes any lists that exist as a sublist of another list in nums."""
    return [
        b for i, b in enumerate(nums)
        if all(not is_subsequence(a, b) for j, a in enumerate(nums) if i != j)
    ]


def main() -> None:
    nums = [[8, 7, 5, 6, 8], [6, 4, 6, 3], [4, 6], [8, 7, 5, 6], [7], [6, 4, 35]]
    print(f'{nums = }')
    new_nums = get_unique_lists(nums)
    print(f'{new_nums = }')


if __name__ == '__main__':
    main()

輸出:

nums = [[8, 7, 5, 6, 8], [6, 4, 6, 3], [4, 6], [8, 7, 5, 6], [7], [6, 4, 35]]
new_nums = [[8, 7, 5, 6, 8], [6, 4, 6, 3], [6, 4, 35]]

暫無
暫無

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

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