Home > Software engineering >  How to use Multiple FOR loops in a single line with if statement
How to use Multiple FOR loops in a single line with if statement

Time:12-01

Can I get a simplified one-liner text for this nested FOR loop below

for w in train_words:
    for t_letter in range(len(TRAIN_LETTERS)):
        if TRAIN_LETTERS[t_letter] == w[0]:
            init_prob[t_letter]  =1

CodePudding user response:

You can do:

init_prob = [sum(1 for w in train_words if t_letter==w[0]) for t_letter in TRAIN_LETTERS]

In the future, you need to provide a minimally reproducible example.

CodePudding user response:

If you also want the index use enumerate:

for t_letter, w in enumerate(train_wrods):
    if TRAIN_LETTERS[t_letter] == w[0]:
        init_prob[t_letter]  =1
  • Related