簡體   English   中英

如何從列表中刪除元組?

[英]How to remove tuple from the list?

大家。 我有一個關於如何從python列表中刪除勾股三元組的問題。 具體問題要求我創建一個包含畢達哥拉斯三元組的列表,但是每個三元組只能出現一次。 我的功能如下:

import numpy as np

def list_pythagorean_triples(amin,cmax):

    x=list(range(amin,cmax))
    y=[]
    for a in x:
        for b in x:
            c=np.sqrt(a**2+b**2)
            if  c==int(c) and c<=cmax:
                s=a,b,int(c)
                y.append(s)      
    return y

U = list_pythagorean_triples(3,12)

U.sort()

print(U)

結果是[(3, 4, 5), (4, 3, 5), (6, 8, 10), (8, 6, 10)] 但是,期望的值應該是[(3, 4, 5), (6, 8, 10)]

有修改代碼的想法嗎? 非常感謝你!

您可以使用一個集合並對元組中的值進行排序,以避免重復:

import numpy as np

def list_pythagorean_triples(amin,cmax):

    x=list(range(amin,cmax))
    y=set() # use a set
    for a in x:
        for b in x:
            c=np.sqrt(a**2+b**2)
            if  c==int(c) and c<=cmax:
                s= (min(a,b), max(a,b), int(c))  # order tuple content by size
                y.add(s)  # sets use add, not append
    return list(y)

U = list_pythagorean_triples(3,12)

U.sort()

print(U)

輸出:

[(3, 4, 5), (6, 8, 10)]

解決此問題的幾種方法:

您可以先對元組進行排序,然后再進行重復數據刪除

def list_pythagorean_triples(amin,cmax):
    x=range(amin,cmax)
    y=[]
    for a in x:
        for b in x:
            c=np.sqrt(a**2+b**2)
            if  c==int(c) and c<=cmax:
                s=a,b,int(c)
                y.append(sorted(s))      
    return sorted(set(y))

或者更好的是,您只能使用大於ab值。

def list_pythagorean_triples(amin,cmax):
    x=range(amin,cmax)
    y=[]
    for a in x:
        for b in range(a,cmax):
            c=np.sqrt(a**2+b**2)
            if  c==int(c) and c<=cmax:
                s=a,b,int(c)
                y.append(s)      
    return y

暫無
暫無

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

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