簡體   English   中英

您如何更改集合中的特定元素?

[英]How do you change a specific element of a set?

在這段代碼中,我試圖將每次循環的集合的值與參數中傳遞的值(在本例中為a)進行比較。 但是有趣的是,它顯示了當我為每個循環使用a時,每個元素都是整數。 如何獲得沒有控制台錯誤的整數到整數比較?

def remove(s,a,b):
    c=set()
    c=s
    for element in c:
        element=int(element)
        if(element<a or element>b):
            c.discard(element)
    return c

def main():
    remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

main()

輸出:

    if(element<=a or element>=b):
TypeError: '>=' not supported between instances of 'int' and 'set'

您重新分配本地變量b

def remove(s,a,b):
    b=set()  # now b is no longer the b you pass in, but an empty set
    b=s  # now it is the set s that you passed as an argument
    # ...    
    if(... element > b): # so the comparison must fail: int > set ??

使用集合理解的簡短實現:

def remove(s, a, b):
    return {x for x in s if a <= x <= b}

>>> remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)
{9, 2, 3, 4}

如果要int進行int比較,則將b作為s的列表。

def remove(s,a,b):
    b = list(s)
    for element in s:
        element=int(element)      
        if(element< a or element > b):
            b.remove(element)
    return b

def main():
    remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

main()

來吧,為什么我們不縮短代碼呢?

嘗試這個:

def remove(s, a, b):
    return s.difference(filter(lambda x: not int(a) < int(x) < int(b), s))


def main():
    new_set = remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

    # {2, 3, 4, 9}
    print(new_set)


main()

暫無
暫無

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

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