python 改变 for_loop 列表理解
python change for_loop in list comprehesion
我得到的代码如下:
ix=0
list_test=[]
for el in parse_data_2['var_nm_final']:
if el=='URI':
ix+=1
list_test.append(ix)
else:
list_test.append(None)
parse_data_2是我的DF。作为输出,我想根据我的情况接收带有 ix 或 None 增量值的列表。意思是这样的
1
None
None
None
None
2
None
3
None
None
None
None
4
...等等
我试过将此循环转换为列表理解,如下所示:
[ix+=1 if el=='URI'else None for el in parse_data_2['var_nm_final']]
但出现错误
[ix+=1 if el=='URI'else None for el in parse_data_2['var_nm_final']]
^
SyntaxError: invalid syntax
你能解释一下我的代码的问题吗?
这是 the walrus operator 的一个很好的用例!
但是,请不要这样做。无论您想完成什么,这几乎可以肯定地以 pythonic 和 高效的方式完成。
[(ix:=ix+1) if el=='URI'else None for el in parse_data_2['var_nm_final']]
在 itertools.count
上使用 next
(或仅 range
且上限较大):
>>> parse_data_2 = {'var_nm_final': ["URI", "foo", "bar", "URI", "URI", "blub", "URI"]}
>>> import itertools
>>> cnt = itertools.count(1)
>>> [next(cnt) if el == "URI" else None for el in parse_data_2["var_nm_final"]]
[1, None, None, 2, 3, None, 4]
我得到的代码如下:
ix=0
list_test=[]
for el in parse_data_2['var_nm_final']:
if el=='URI':
ix+=1
list_test.append(ix)
else:
list_test.append(None)
parse_data_2是我的DF。作为输出,我想根据我的情况接收带有 ix 或 None 增量值的列表。意思是这样的
1
None
None
None
None
2
None
3
None
None
None
None
4
...等等
我试过将此循环转换为列表理解,如下所示:
[ix+=1 if el=='URI'else None for el in parse_data_2['var_nm_final']]
但出现错误
[ix+=1 if el=='URI'else None for el in parse_data_2['var_nm_final']]
^
SyntaxError: invalid syntax
你能解释一下我的代码的问题吗?
这是 the walrus operator 的一个很好的用例! 但是,请不要这样做。无论您想完成什么,这几乎可以肯定地以 pythonic 和 高效的方式完成。
[(ix:=ix+1) if el=='URI'else None for el in parse_data_2['var_nm_final']]
在 itertools.count
上使用 next
(或仅 range
且上限较大):
>>> parse_data_2 = {'var_nm_final': ["URI", "foo", "bar", "URI", "URI", "blub", "URI"]}
>>> import itertools
>>> cnt = itertools.count(1)
>>> [next(cnt) if el == "URI" else None for el in parse_data_2["var_nm_final"]]
[1, None, None, 2, 3, None, 4]