python - 用计数替换空白字符串

标签 python list-comprehension

假设我有一个这样的列表:

py = ['','','','','monty','','','','python',]

我想将其映射到此:

[4,'monty',3,'python']

有人知道一个聪明的解决方案吗?我能够弄清楚将其转换为:

[1,1,1,1,'monty',1,1,1,'python',]

使用:

quotes = [x if x else 1 for x in quotes]

最佳答案

我认为Rob's solution是最好的:最具可读性且最容易理解。我修复了它,因为最后一个元素为空,并更改为生成器(它比使用 append 更有效):

def blank_to_count(iterable):
    counter = 0
    for val in iterable:
        if val == '':
            counter += 1
        else:
            if counter > 0: yield counter  # yield count of blank elements
            counter = 0
            yield val  # yield current non-blank element
    if counter > 0: yield counter  # in case last element was blank

py = ['','','','','monty','','','','python',]
print(list(blank_to_count(py)))  # [4, 'monty', 3, 'python']

py = ['monty','','','','python']
print(list(blank_to_count(py)))  # ['monty', 3, 'python']

py = ['','','','','monty','','','','python','','']
print(list(blank_to_count(py)))  # [4, 'monty', 3, 'python', 2]

关于python - 用计数替换空白字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335931/

相关文章:

python - 如何修复内部网格 - Matplotlib 子图

python - Tkinter 如何绑定(bind)到 shift+tab

python - 狮身人面像 : "WARNING: py:class reference target not found" for class variable

python - 使多个 if 语句不那么冗长

python - 遍历多个列表的相应元素

python - 使用生成器作为 sorted() 的输入而不是列表理解是否值得

python - 为什么 np.linspace(1,5,5, dtype = int, endpoint=False) 会导致包含 1 两次的数组?

python - 使用列表理解在python中连接字典中的项目

python - 对元组列表中的每个值求和

python - 在 Heroku 上部署时,报 TypeError : expected str, bytes or os.PathLike object, not tuple