def make_unique(original_list):unique_list = [][unique_list.append(obj) for obj in original_list if obj not in unique_list]return unique_list
有些人可能认为带有副作用的列表理解不是一个好的解决方案。这里有一个替代方案:
def make_unique(original_list):unique_list = []map(lambda x: unique_list.append(x) if (x not in unique_list) else False, original_list)return unique_list
def GetListWithoutRepetitions(loInput):# return list, consisting of elements of list/tuple loInput, without repetitions.# Example: GetListWithoutRepetitions([None,None,1,1,2,2,3,3,3])# Returns: [None, 1, 2, 3]
if loInput==[]:return []
loOutput = []
if loInput[0] is None:oGroupElement=1else: # loInput[0]<>NoneoGroupElement=None
for oElement in loInput:if oElement<>oGroupElement:loOutput.append(oElement)oGroupElement = oElementreturn loOutput
def remove_duplicates(item_list):''' Removes duplicate items from a list '''singles_list = []for element in item_list:if element not in singles_list:singles_list.append(element)return singles_list
def ordered_set(in_list):out_list = []added = set()for val in in_list:if not val in added:out_list.append(val)added.add(val)return out_list
为了比较效率,我使用了100个整数的随机样本-62个是唯一的
from random import randintx = [randint(0,100) for _ in xrange(100)]
In [131]: len(set(x))Out[131]: 62
这是测量的结果
In [129]: %timeit list(OrderedDict.fromkeys(x))10000 loops, best of 3: 86.4 us per loop
In [130]: %timeit ordered_set(x)100000 loops, best of 3: 15.1 us per loop
那么,如果将set从溶液中移除会发生什么?
def ordered_set(inlist):out_list = []for val in inlist:if not val in out_list:out_list.append(val)return out_list
结果没有订单号那么糟糕,但仍然是原始解决方案的3倍以上
In [136]: %timeit ordered_set(x)10000 loops, best of 3: 52.6 us per loop
>>> reduce(lambda r, v: v in r and r or r + [v], l, [])[5, 6, 1, 2, 3, 4]
5倍更快但更复杂
>>> reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0][5, 6, 1, 2, 3, 4]
说明:
default = (list(), set())# user list to keep order# use set to make lookup faster
def reducer(result, item):if item not in result[1]:result[0].append(item)result[1].add(item)return result
reduce(reducer, l, default)[0]
# from functools import reduce <-- add this import on Python 3
def uniq(iterable, key=lambda x: x):"""Remove duplicates from an iterable. Preserves order.:type iterable: Iterable[Ord => A]:param iterable: an iterable of objects of any orderable type:type key: Callable[A] -> (Ord => B):param key: optional argument; by default an item (A) is discardedif another item (B), such that A == B, has already been encountered and taken.If you provide a key, this condition changes to key(A) == key(B); the callablemust return orderable objects."""# Enumerate the list to restore order lately; reduce the sorted list; restore orderdef append_unique(acc, item):return acc if key(acc[-1][1]) == key(item[1]) else acc.append(item) or accsrt_enum = sorted(enumerate(iterable), key=lambda item: key(item[1]))return [item[1] for item in sorted(reduce(append_unique, srt_enum, [srt_enum[0]]))]
def deduplicate(sequence):visited = set()adder = visited.add # get rid of qualification overheadout = [adder(item) or item for item in sequence if item not in visited]return out
In [1]: a = ["apples", "bananas", "cucumbers"]
In [2]: b = ["pears", "apples", "watermelons"]
In [3]: set(a).symmetric_difference(b).union(set(a).intersection(b))Out[3]: {'apples', 'bananas', 'cucumbers', 'pears', 'watermelons'}
def remove_dup(arr):size = len(arr)j = 0 # To store index of next unique elementfor i in range(0, size-1):# If current element is not equal# to next element then store that# current elementif(arr[i] != arr[i+1]):arr[j] = arr[i]j+=1
arr[j] = arr[size-1] # Store the last element as whether it is unique or repeated, it hasn't stored previously
return arr[0:j+1]
if __name__ == '__main__':arr = [10, 10, 1, 1, 1, 3, 3, 4, 5, 6, 7, 8, 8, 9]print(remove_dup(sorted(arr)))
def uniq(iterable, key=lambda x: x):seens = set()seenl = []for item in iterable:k = key(item)try:seen = k in seensexcept TypeError:seen = k in seenlif not seen:yield itemtry:seens.add(k)except TypeError:seenl.append(k)
def remove_duplicates(input_list):if input_list == []:return []#sort list from smallest to largestinput_list=sorted(input_list)#initialize ouput list with first element of the sorted input listoutput_list = [input_list[0]]for item in input_list:if item >output_list[-1]:output_list.append(item)return output_list
line=[['16.4966155686595', '-27.59776154691', '52.3786295521147'],['16.4966155686595', '-27.59776154691', '52.3786295521147'],['17.6508629295574', '-27.143305738671', '47.534955022564'],['17.6508629295574', '-27.143305738671', '47.534955022564'],['18.8051102904552', '-26.688849930432', '42.6912804930134'],['18.8051102904552', '-26.688849930432', '42.6912804930134'],['19.5504702331098', '-26.205884452727', '37.7709192714727'],['19.5504702331098', '-26.205884452727', '37.7709192714727'],['20.2929416861422', '-25.722717575124', '32.8500163147157'],['20.2929416861422', '-25.722717575124', '32.8500163147157']]
tuple_line = [tuple(pt) for pt in line] # convert list of list into list of tupletuple_new_line = sorted(set(tuple_line),key=tuple_line.index) # remove duplicated elementnew_line = [list(t) for t in tuple_new_line] # convert list of tuple into list of list
print (new_line)
from collections import OrderedDict, Counter
class Container:def __init__(self, obj):self.obj = objdef __eq__(self, obj):return self.obj == objdef __hash__(self):try:return hash(self.obj)except:return id(self.obj)
class OrderedCounter(Counter, OrderedDict):'Counter that remembers the order elements are first encountered'
def __repr__(self):return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):return self.__class__, (OrderedDict(self),)
def remd(sequence):cnt = Counter()for x in sequence:cnt[Container(x)] += 1return [item.obj for item in cnt]
def oremd(sequence):cnt = OrderedCounter()for x in sequence:cnt[Container(x)] += 1return [item.obj for item in cnt]
def unique(items: Iterable[T]) -> Iterable[T]:"""For unhashable items (can't use set to unique) with a partial order"""yield from map(operator.itemgetter(0), itertools.groupby(sorted(items)))
Write a Python program to create a list of numbers by taking input from the user and then remove the duplicates from the list. You can take input of non-zero numbers, with an appropriate prompt, from the user until the user enters a zero to create the list assuming that the numbers are non-zero.Sample Input: [10, 34, 18, 10, 12, 34, 18, 20, 25, 20]Output: [10, 34, 18, 12, 20, 25]
lst = []print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")print("ENTER LIST ELEMENTS :: ")while True:n = int(input())if n == 0 :print("!!!!!!!!!!! EXIT !!!!!!!!!!!!")breakelse :lst.append(n)print("LIST ELEMENR ARE :: ",lst)#dup = set()uniq = []for x in lst:if x not in uniq:uniq.append(x)# dup.add(x)print("UNIQUE ELEMENTS IN LIST ARE :: ",uniq)