-1

Hello, Let's say I have a list called values that contains some dupliated elements [330, 210, 130, 60, 0, 240, 280, 1300, 740, 640, 520, 430, 240, 240, 240, 200, 200]. I want to get the index of each element even it's the duplicated ones. Here is what I did

l = []
for item in values:
    if item < t_max:
        l.append(values.index(item))

but it gives the following result

0
1
2
3
4
5
6
8
9
10
11
5
5
5
15
15

Any idea how to preceed? Thank you.

OneManArmy
  • 33
  • 7

4 Answers4

2

Try this:

from collections import defaultdict
dct = defaultdict(list)

value = [330, 210, 130, 60, 0, 240, 280, 1300, 740, 640, 520, 430, 240, 240, 240, 200, 200]

for idx, v in enumerate(value):
    dct[v].append(idx)
    
print(dct)

Output:

defaultdict(list,
            {330: [0],
             210: [1],
             130: [2],
             60: [3],
             0: [4],
             240: [5, 12, 13, 14],
             280: [6],
             1300: [7],
             740: [8],
             640: [9],
             520: [10],
             430: [11],
             200: [15, 16]})
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1

Try enumerate instead:

for index, item in enumerate(values):
    if item < t_max:
        l.append(index)

Your code doesn't work because index takes the first occurrence of a value in a list, but in your list they're duplicate values.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Considering your tmax as sample 200

data = [330, 210, 130, 60, 0, 240, 280, 1300, 740, 640, 520, 430, 240, 240, 240, 200, 200]

l = []

for index, item in enumerate(data):
    if item < 200:
        l.append(index)
        print(index,item)

print(l)

will give

2 130
3 60
4 0
[2, 3, 4]
0

Use a list comprehension:

l = [i for i in range(len(lst)) if lst[i] in lst[:i]]

Or better use a dictionary:

d = dict()
for index, value in enumerate(lst):
    d[value] = d.get(value, []) + [index]

object d will refer to:

{330: [0], 210: [1], 130: [2], 60: [3], 0: [4], 240: [5, 12, 13, 14], 280: [6], 1300: [7], 740: [8], 640: [9], 520: [10], 430: [11], 200: [15, 16]}
Nothing special
  • 415
  • 3
  • 8