# Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.05 KB  |  hits: 12  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. How do I keep the index of the duplicate element unchanged
2. ['a', 'b', 'b', 'c', 'c', 'd']
3.
4. [[0, 'a'], [1, 'b'],  [1, 'b'], [2, 'c'], [2, 'c'], [3, 'd']]
5.
6. >>> map(lambda (index, word): [index, word], enumerate([['a', 'b', 'b', 'c', 'c', 'd']])
7. [[0, 'a'], [1, 'b'], [2, 'b'], [3, 'c'], [4, 'c'], [5, 'd']]
8.
9. input = ['a', 'b', 'b', 'c', 'c', 'd']
10. mapping = { v:i for (i, v) in enumerate(sorted(set(input))) }
11. [ [mapping[v], v] for v in input ]
12.
13. [ [d.setdefault(v, len(d)), v] for d in [{}] for v in input ]
14.
15. >>> import itertools
16. >>> seq = ['a', 'b', 'b', 'c', 'c', 'd']
17. >>> [[i, c] for i, (k, g) in enumerate(itertools.groupby(seq)) for c in g]
18. [[0, 'a'], [1, 'b'], [1, 'b'], [2, 'c'], [2, 'c'], [3, 'd']]
19.
20. [
21.     [i, x]
22.     for i, (value, group) in enumerate(itertools.groupby(['a', 'b', 'b', 'c', 'c', 'd']))
23.     for x in group
24. ]
25.
26. a = ['a', 'b', 'b', 'c', 'c', 'd']
27. result = []
28. d = {}
29. n = 0
30. for k in a:
31.   if k not in d:
32.      d[k] = n
33.      n += 1
34.   result.append([d[k],k])
35.
36. [[0, 'a'], [1, 'b'], [1, 'b'], [2, 'c'], [2, 'c'], [3, 'd'], [0, 'a']]