简体   繁体   English

在嵌套 for 循环中枚举外部增量的列表理解

[英]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.其中increment值需要为 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)使用enumerate(..., start=1)从 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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