繁体   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