繁体   English   中英

以根据值具有不同格式的格式化方式打印值?

[英]Printing values in a formatted way that has different formats depending on value?

我对 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 语句想多了。 无论如何,这是否会更快更容易?

对于您可能需要在一次迭代中从列表中获取多个元素的情况,迭代器通常是一种可行的解决方案。 在任何可迭代对象(列表、字符串、字典、生成器iter()上调用内置的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'

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM