Reputation: 151
I have a list of tuples :
list = [(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 6'), (u'RHSA-2017:1271', u'Red Hat Enterprise Linux 6'), (u'RHSA-2017:1270', u'Red Hat Enterprise Linux 7')]
i need to compare index1 element for each tuple i.e
'Red Hat Enterprise Linux 6'
which is the same for the first 2 tuples
and the first index element in tuple 3 ,which is :
'Red Hat Enterprise Linux 7'
my goal is once i detected that element index 1 in tuple 2 is duplicate
remove this tuple from the list.
i have tried to create anew list with the required tuples by i am getting
an empty list
new_list = []
for i in list:
rhel_ver = str(i[1])
if rhel_ver not in i:
new_list.append(i)
getting empty list. how can i get only the first tuple that contains the rhel version ,i.e:
list = [(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 6'), (u'RHSA-2017:1270', u'Red Hat Enterprise Linux 7')]
Upvotes: 1
Views: 92
Reputation: 199
You can use python OrderedDict to create a new list setting the index 1 (second element in the tuple) as key. This will remove any duplicate. You can then produce a new list from the Ordered Dict. python 2.7
import collections
tagPairs=collections.OrderedDict()
lst = [(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 6'),
(u'RHSA-2017:1271', u'Red Hat Enterprise Linux 6'),
(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 7')]
for i,v in lst:
tagPairs[v]=i
unique_list=[]
for k,j in tagPairs.items():
unique_list.append((j,k))
print unique_list
Upvotes: 0
Reputation: 3012
You can use the any
built-in to make a new unique list:
my_list = [(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 6'), (u'RHSA-2017:1271', u'Red Hat Enterprise Linux 6'),
(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 7')]
unique_list = []
for element in my_list:
if not any(tup[1] == element[1] for tup in unique_list):
unique_list.append(element)
print(unique_list)
Upvotes: 2
Reputation: 82929
You can keep track of the elements you've already seen in a set
:
lst = [(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 6'),
(u'RHSA-2017:1271', u'Red Hat Enterprise Linux 6'),
(u'RHSA-2017:1270', u'Red Hat Enterprise Linux 7')]
seen = set()
result = []
for rhsa, name in lst:
if name not in seen:
result.append((rhsa, name))
seen.add(name)
print(result)
# [('RHSA-2017:1270', 'Red Hat Enterprise Linux 6'), ('RHSA-2017:1270', 'Red Hat Enterprise Linux 7')]
Upvotes: 2