still_learning
still_learning

Reputation: 806

Multiple if/else conditions to check last characters in a list of strings

I have this list

num_list=["mille", "duemila", "tremila", "quattromila", "cinquemila", "seimila", "settemila", "ottomila", "novemila", "diecimila", "milione", "miliardo", "milioni",'miliardi','mila']

I would like to build the following list

output=['millesimo', 'duemillesimo','tremillesimo','quattromillesimo','cinquemillesimo','seimillesimo','settemillesimo', 'ottomillesimo', 'novemillesimo', 'diecimillesimo', 'milionesimo', 'miliardesimo', 'milionesimo','miliardesimo']

This should be built by following the conditions below, after removing the last character from each string:

I started to do as follows:

numeri_card_esimo = [x[:-1] + 'lesimo' if x[:-2] == 'll' else x[:-1] + 'esimo' for x in numeri_card_esimo]

and the output is not so close to that one I would like:

['millesimo',
 'duemilesimo', # it should be duemillesimo
 'tremilesimo', # same as above
 'quattromilesimo', # same as above
 'cinquemilesimo', # same as above
 'seimilesimo', # same as above
 'settemilesimo', # same as above
 'ottomilesimo', # same as above
 'novemilesimo', # same as above
 'diecimilesimo', # same as above
 'milionesimo',
 'miliardesimo',
 'milionesimo',
 'milesimo'] # it should be excluded

but it does not work because of wrong use of if/else conditions. How should I write these conditions?

Upvotes: 2

Views: 668

Answers (1)

taha
taha

Reputation: 722

In my opinion, the logic you are trying to apply is a bit long to be used in a list comprehension. It is better to move it into a function for the sake of readability.

def convert(num):
    num = num[:-1]
    if num[-2:]=='ll' or num=='milion' or num=='miliard':
        num = num + 'esimo'
    elif word[-1]=='l':
        num = num + 'lesimo'
    return num

num_list=["mille", "duemila", "tremila", "quattromila", "cinquemila", "seimila", "settemila", "ottomila", "novemila", "diecimila", "milione", "miliardo", "milioni",'miliardi','mila']

# Remove mila occurrences
num_list = [num for num in num_list if num!='mila']
output = [convert(num) for num in num_list]
print(output)

Upvotes: 1

Related Questions