[英]how do i incorporate a set into this Python code so it can work the same way as it does already
此代碼輸入數字列表,僅輸出列表中具有正號和負號的數字。 因此,例如,它輸入列表(2,3,4,-2,-3),而輸出為(2,3,-2,-3)。
此功能確實有效,但是我正在尋找如何使此功能輸出一個set
,以確保沒有重復。
def pos_neg(a):
return [i for i in a if -i in a]
總結兩個評論,您可以將括號替換為大括號:
def pos_neg(a):
return {i for i in a if -i in a}
或者,為了更快地處理長列表,請執行以下操作:
def pos_neg(a):
return {-i for i in a}.intersection(a)
或者,如果您想再次返回列表:
def pos_neg(a):
return list({-i for i in a}.intersection(a))
但是,返回的列表將不被排序。 如果要返回有序列表(按大小):
def pos_neg(a):
return sorted({-i for i in a}.intersection(a))
如果要返回保留原始順序的列表,請執行以下操作:
from collections import OrderedDict
def pos_neg(a):
s = set(a)
return list(OrderedDict.fromkeys(i for i in a if -i in s))
或者,如果您不想使用OrderedDict:
def pos_neg(a):
s = set(a)
t = set()
b = []
for i in a:
if -i in s and i not in t:
t.add(i)
b.append(i)
return b
或者,如果您想使用列表理解:
def pos_neg(a):
s = set(a)
t = set()
return [i for i in a if -i in s and not (i in t or t.add(i))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.