首页 > 解决方案 > 以根据值具有不同格式的格式化方式打印值?

问题描述

我对python还是比较陌生,只是想知道如何从一个函数中打印值,该函数将列表作为输入并打印每个值,每个值用逗号分隔,每两个值分隔,除了-1,它只是自己打印(假设有如果不是-1,则将始终是两个匹配在一起的值)。

一些例子是:输入:[2,3,4,2,-1,4,3] 输出:2 3, 4 2, -1, 4 3

输入:[2,1,-1] 输出:2 1, -1

每次解决方案时,我都会觉得我在用 while 循环和 if 语句过度思考它。无论如何,这是否会更快更容易?

标签: pythonpython-3.x

解决方案


对于可能需要在一次迭代中从列表中获取多个元素的情况,迭代器通常是一种可行的解决方案。在任何可迭代对象(列表、字符串、字典、生成器)上调用内置iter()函数将提供一个迭代器,该迭代器一次动态地返回一个对象,并且不能回溯。如果您随后将迭代器分配给变量并在for循环中使用该变量,您可以自己有选择地调用next()它以使循环“跳过”元素:

inp = [2,3,4,2,-1,4,3]
inp_iter = iter(inp)
output = []
for elem in inp_iter:  # each iteration essentially calls next() on the iterator until there is no more next()
    if elem == -1:
        output.append(str(elem))
    else:
        # withdraw the next element from the iterator before the `for` loop does automatically
        # thus, the for loop will skip this element
        next_elem = next(inp_iter)
        output.append(f"{elem} {next_elem}")
print(', '.join(output))
# '2 3, 4 2, -1, 4 3'

您需要为此添加错误处理以处理边缘情况,但这应该可以解决您的直接问题。


推荐阅读