lundi 30 mars 2020

How to convert list append with for, if, elif to list comprehension

I' like to convert list append code with mulitple for and if, elif to list comprehension. I tried but only temp_list worked. temp_list2 did not work properly

Original code

temp_list = []
temp_array = accd['ACCD_SEQ'].values
temp_list = [i for i in temp_array if len(accd[accd['ACCD_DTL'].str.contains(i)]) != 0]

temp_list2 = []

for i in temp_list:
    if len(accd[accd['ACCD_DTL'].str.contains(i)]) == 1:
        temp_list2.append(i)
    elif len(accd[accd['ACCD_DTL'].str.contains(i)]) > 1:
        for j in range(len(accd[accd['ACCD_DTL'].str.contains(i)])):
            temp_list2.append(i)
    else:
        pass

My trial

temp_list2 = [i if len(accd[accd['ACCD_DTL'].str.contains(i)]) == 1 else i for j in range (len(accd[accd['ACCD_DTL'].str.contains(i)])) if len(accd[accd['ACCD_DTL'].str.contains(i)]) > 1 for i in temp_list

This code said "UnboundLocalError : local variable 'i' referenced before assignment"

Anyone can help to fix it?

Aucun commentaire:

Enregistrer un commentaire