如何修改列表理解中的外部变量?

问题描述 投票:0回答:1

Python代码:

i: int = 1
table: list = [[i, bit, None, None ] for bit in h]
del i
del bit

预期行为:

i: int = 1
table: list = [[i++, bit, None, None ] for bit in h] # the i needs to be incremented by 1 per iteration
del i
del bit
python-3.x list-comprehension variable-assignment
1个回答
0
投票

在这种情况下,请使用

enumerate
:

h = '10010010'  # Undefined in OP example.  Just something to enumerate.
table = [[i, bit, None, None ] for i, bit in enumerate(h, start=1)]
for row in table:
    print(row)

输出:

[1, '1', None, None]
[2, '0', None, None]
[3, '0', None, None]
[4, '1', None, None]
[5, '0', None, None]
[6, '0', None, None]
[7, '1', None, None]
[8, '0', None, None]
© www.soinside.com 2019 - 2024. All rights reserved.