Take the 2-minute tour ×  I have a list in the following format:
L = ['apples oranges  x',      'bananas apples  y',      'apples
oranges  z']  For every item in L, if item.split()[0:2] matches
another item.split()[0:2] (i.e., 'apples oranges' matches
'apples oranges') then I need to output a single
item.split()[0:2] followed by the tags recording the origin of
the partially duplicated line. The tags come from index 3 of
each item (i.e, x, y or z).  So, the output of L would be L2:
L2 = ['apples oranges x z',      'bananas apples y']  Any ideas?
share|improve this question add comment  1 Answer  up vote 4
down vote accepted d = collections.defaultdict(list)  for line
in L:     name, value = line.rsplit(' ',1)  then you'll have a
dict like that:  {'bananas apples ': ['y'], 'apples oranges ':
['x', 'z']}  So you only need to format the keys and values:
[key + ' '.join(values) for key, values in d.items()]  And the
result will be:  ['bananas apples y', 'apples oranges x z']
share|improve this answer Very con