简体   繁体   中英

Enumerate in nested for loop with list comprehension for outer increment

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)

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,
    )
]

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM