Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Can Multiple if-condition and append be simplified

If it is possible to simplify the following code.

c0, c1, c2, c3, c4, c5, c6, c7, c8, c9 = ([] for _ in range(10))
  
  for i in dataset:
    if i[1] == 0:
      c0.append(i)
    elif i[1] == 1:
      c1.append(i)
    elif i[1] == 2:
      c2.append(i)
    elif i[1] == 3:
      c3.append(i)
    elif i[1] == 4:
      c4.append(i)
    elif i[1] == 5:
      c5.append(i)
    elif i[1] == 6:
      c6.append(i)
    elif i[1] == 7:
      c7.append(i)
    elif i[1] == 8:
      c8.append(i)
    else:
      c9.append(i)

Trying to divide the whole dataset into class-wise multiple datasets. Code below is just for example which has only 10 classes, but the dataset I'm working on has massive numbers of classes, so need to simplify as possible.

like image 617
이재환 Avatar asked Sep 29 '21 06:09

이재환


1 Answers

Better with a list:

lsts = [c0, c1, c2, c3, c4, c5, c6, c7, c8]
for i in dataset:
    if i[1] < len(lsts):
        lsts[i[1]].append(i)
    else:
        c9.append(i)

And the lists will contain what you want :)

like image 169
U12-Forward Avatar answered Oct 19 '22 08:10

U12-Forward