Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

590
Views
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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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 :)

over 4 years ago · Santiago Trujillo Report

0

How about like this?

Use dictionary instead of nested lists like c0, c1, c2

c = {x:[] for x in range(10)}
  
for i in dataset:
    c[i[1]].append(i)

If you want to append other items in the dataset to the c9 as like you mentioned in your question, then

for i in dataset:
    if 0 <= i[1] <= 8:
        c[i[1]].append(i)
    else:
        c[9].append(i)
over 4 years ago · Santiago Trujillo Report

0

you can use it.

# if you need cX as var
c0, c1, c2, c3, c4, c5, c6, c7, c8, c9 = ([] for _ in range(10))
database = {0: c0,
            1: c1,
            2: c2,
            ...,
            9: c9}

# else
database = {i: [] for i in range(10)}

for i in dataset:
    if i[1] in dataset:
        database[i].append(i)
    else:
        database[9].append(i)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!