How to write a function that accepts an arbitrary number of lists and returns a single list with exactly one occurrence of each element that appears in any of the input lists? For example:
list1 = [1,2,3,1,3,5]
list2 = [2,3,4,"a","b"]
list3 = [4,5,6,"b","c]
# and the result:
result_list = [1,2,3,4,5,6,"a","b","c"]
I'm looking for a function with perhaps an indefinite number of arguments passed by keyword.
combine them then make it a set which removes duplicates and then convert it back to a list again
list1 = [1,2,3,1,3,5]
list2 = [2,3,4,'a','b']
list3 = [4,5,6,'b','c']
print(list(set(list1 + list2 + list3)))
If you want it like a function maybe something like this, you can pass in as many lists as you like
def unique_list(*args):
l = []
[l.extend(x) for x in args]
return list(set(l))
if __name__ == '__main__':
new_list = unique_list([1,2,3,1,3,5], [2,3,4,'a','b'], [4,5,6,'b','c'])
print(new_list)
Try this,
def combine_lists(*argv):
sum_lst = []
for lst in argv:
sum_lst += lst
return list(set(sum_lst))
Results
In [58]: combine_lists(list1,list2,list3)
Out[58]: ['a', 1, 2, 3, 4, 5, 6, 'c', 'b']
In [59]: combine_lists(list1,list2,list3,list2,list1)
Out[59]: ['a', 1, 2, 3, 4, 5, 6, 'c', 'b']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.