-1

input: [("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]

expected output: [("abc", 1, "def"), ("bc", 2, "a"), ("bc", 3, "a")]

I was trying something like:- field_list = [field for i, field in enumerate(field_list) for cmp_field in field_list[i+1:] if].....don't know how if would suit here?

I wanted to achieve this using list comprehension. Logic for getting output -- remove the duplicates(tuple is treated as duplicate if item[0] and item[1] are same).

I could achieve it using traditional for loops but I would like to get this with list comprehension. Any thoughts?

Edit: ("abc", 1, "def") and ("abc", 1, "ghi") are duplicates, so I can pick the first one.

Barun Sharma
  • 1,452
  • 2
  • 15
  • 20

3 Answers3

1
output = [(x, y, z) for j, (x, y, z) in enumerate(input) if (x, y) not in [(x2, y2) for x2, y2, _ in input[:j]]]
# output = [('abc', 1, 'def'), ('bc', 2, 'a'), ('bc', 3, 'a')]

However, it might be more efficient with a traditional for loop, since you would not need to build the second list at each iteration (or a set as suggested by Ashwini Chaudhary).

Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
1

Taking inspiration from this, you might try

inp = [("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]
res = []
[res.append(el) for el in inp if not [tmp for tmp in res if tmp[0] == el[0] and tmp[1] == el[1]]]

Although I believe regular for loops would be better for your situation.

Community
  • 1
  • 1
Simone Bronzini
  • 1,057
  • 1
  • 12
  • 23
0

I used groupby which is an intermediate step. .

In [40]: l=[("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]

In [41]: from itertools import groupby

In [42]: groups=[list(g) for k,g in groupby(l,key=itemgetter(1))]

In [43]: groups
Out[43]: 
[[('abc', 1, 'def'), ('abc', 1, 'ghi')],
 [('bc', 2, 'a'), ('bc', 2, 'b')],
 [('bc', 3, 'a')]]

In [44]: [elem[0] for elem in groups]
Out[44]: [('abc', 1, 'def'), ('bc', 2, 'a'), ('bc', 3, 'a')]
Ajay
  • 5,267
  • 2
  • 23
  • 30
  • 1
    That wouldn't work with [('abc', 1, 'def'), ('def', 1, 'abc')] – Julien Spronck May 13 '15 at 11:33
  • before grouping we can sort the list 'l' – Ajay May 13 '15 at 11:35
  • 1
    @Ajay: the OP says "tuple is treated as duplicate if item[0] and item[1] are same", not "only if item[1] is the same". Simply change your key. (PS: you could do `next(g)` instead of `list(g)[0]`.) – DSM May 13 '15 at 11:36
  • what would it change? for the input [('abc', 1, 'def'), ('def', 1, 'abc')], the output should be [('abc', 1, 'def'), ('def', 1, 'abc')] – Julien Spronck May 13 '15 at 11:36
  • @DSM Please edit the answer.I didn't get what the questionnaire want and what people are expecting – Ajay May 13 '15 at 11:47