def pos_and_neg(a):
seen = set()
seen_add = seen.add
return [ x for x in a if not (x in seen or seen_add(x))]
print pos_and_neg([1,2,3,-1,-3])
這需要返回如何從字符串單數,同時保留順序
[1,3,-1,-3]
def pos_and_neg(a):
seen = set()
seen_add = seen.add
return [ x for x in a if not (x in seen or seen_add(x))]
print pos_and_neg([1,2,3,-1,-3])
這需要返回如何從字符串單數,同時保留順序
[1,3,-1,-3]
def pos_and_neg(a):
return [ x for x in a if (x*(-1)) in a]
print pos_and_neg([1, 4, 6, -1, -4, -6, 5, 7, -7])
輸出: - [1, 4, 6, -1, -4, -6, 7, -7]
聽起來不錯,但它會工作讓我們說打印pos_and_neg([1, 4,5,6,-1,-4,-6])我只是試圖讓它成爲模塊化的,所以它可以在任何你打印的打印上工作 – 2014-10-16 14:27:52
@NickBergeron檢查更新後的代碼。 – 2014-10-16 14:59:57
@NickBergeron對於[1,4,5,6,-1,-4,-6]'它有輸出: - '[1,4,6,-1,-4,-6]' – 2014-10-16 15:05:07
你可以做這樣的事情
def pos_and_neg(l):
unique = set(l) # use a set for faster lookups
return [i for i in l if (i*-1) in unique]
>>> pos_and_neg([1,4,5,6,-1,2,-4,-6])
[1, 4, 6, -1, -4, -6]
雖然它不會噸處理重複,所以如果你有[1,1,-1]
所有的價值將被保留,而不是刪除1
之一。
你的意思是你只想保留一個值,如果它存在於正面和負面(例如1和-1,3和-3)?如果有重複呢? – CoryKramer 2014-10-16 14:02:07
是的,使它模塊化,以任何打印你通過在它 – 2014-10-16 14:28:31
這裏沒有任何字符串... – geoffspear 2014-10-16 14:29:51