0

I am trying to apply the accepted solution to this question to the problem below but stupidly I cannot:

In:

increment='increment'
[f'{level_A}_{level_B}_{level_C}_{increment}' 
for level_A, rng in [(5, list(range(1,3))), (6, list(range(1,3)))]
for level_B in rng
for level_C in range(1, 5)]

Out:

['5_1_1_increment',
 '5_1_2_increment',
 '5_1_3_increment',
 '5_1_4_increment',
 '5_2_1_increment',
 '5_2_2_increment',
 '5_2_3_increment',
 '5_2_4_increment',
 '6_1_1_increment',
 '6_1_2_increment',
 '6_1_3_increment',
 '6_1_4_increment',
 '6_2_1_increment',
 '6_2_2_increment',
 '6_2_3_increment',
 '6_2_4_increment']

Where the increment values need to be 1,2,3,..15,16. Importantly, I need to do this in a single line (ie no variable definition outside the comprehension) and ideally without any imports (like in the original question's accepted answer)

0

2 Answers 2

2

Use walrus operator for increment.

>>> increment=0
>>> [f'{level_A}_{level_B}_{level_C}_{(increment:=increment+1)}' 
... for level_A, rng in [(5, list(range(1,3))), (6, list(range(1,3)))]
... for level_B in rng
... for level_C in range(1, 5)]

which gives me:

['5_1_1_1', '5_1_2_2', '5_1_3_3', '5_1_4_4', '5_2_1_5', '5_2_2_6', '5_2_3_7', '5_2_4_8', '6_1_1_9', '6_1_2_10', '6_1_3_11', '6_1_4_12', '6_2_1_13', '6_2_2_14', '6_2_3_15', '6_2_4_16']
Sign up to request clarification or add additional context in comments.

Comments

1

Since you need to number them after you generate the combinations, you need to use nested generators/comprehensions:

  • in the inner one, generate the combinations;
  • number them from 1, using enumerate(..., start=1)
  • in the outer one, format them up in the required form.
[
    f"{level_A}_{level_B}_{level_C}_{increment}"
    for increment, (level_A, level_B, level_C) in enumerate(
        (
            (A, B, C)
            for A, rng in [(5, list(range(1, 3))), (6, list(range(1, 3)))]
            for B in rng
            for C in range(1, 5)
        ),
        start=1,
    )
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.