使用列表编译的查询

2024-06-26 00:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张这样的清单

tmp_text = ['col1','','col2','col3','','']

我试图用迭代值替换列表中的空元素,这是我试图获得的输出

tmp_text = ['col1','Nan1','col2','col3','Nan2','Nan3']

基本上,我需要用字符串'NaN'替换空元素,但是要用附加的迭代数替换空元素。我需要一些关于如何做这件事的帮助


Tags: 字符串text元素列表nantmpcol2col3
3条回答

这里有一种方法你可以做到

from itertools import counter
nan_counter = counter(1)

tmp_txt = [s if s else f'NaN{next(nan_counter)}' for s in tmp_txt]

在Python3.8+中使用assignment/walrus操作符可以非常轻松地完成这项工作

tmp_text = ['col1','','col2','col3','','']

i = 0
result = [x or f'Nan{(i:=i+1)}' for x in tmp_text]

['col1', 'Nan1', 'col2', 'col3', 'Nan2', 'Nan3']

您可以使用^{},它返回数字的迭代器:

>>> import itertools
>>> tmp_text = ['col1','','col2','col3','','']
>>> counter = itertools.count(1)
>>> new_text = [x or f'Nan{next(counter)}' for x in tmp_text]
['col1', 'Nan1', 'col2', 'col3', 'Nan2', 'Nan3']

相关问题 更多 >