简体   繁体   English

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

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

I'm still relatively new to python and was just wondering how to print values from a function that takes in a list as input and prints every value with a comma separated by every two values except -1 which it just prints by itself (assuming there will always be two values matched together if its not -1).我对 python 还是比较陌生,只是想知道如何从一个函数打印值,该函数接受一个列表作为输入,并打印每个值,每个值用逗号分隔,每两个值除了 -1 它只是自己打印(假设有如果不是 -1,则总是将两个值匹配在一起)。

Some examples would be: input: [2,3,4,2,-1,4,3] output: 2 3, 4 2, -1, 4 3一些例子是:输入: [2,3,4,2,-1,4,3]输出: 2 3, 4 2, -1, 4 3

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

Every time a solution it feels like I'm overthinking it with while loops and if statements.每次解决方案时,我都觉得我用 while 循环和 if 语句想多了。 Is there anyway for this to be faster and easier?无论如何,这是否会更快更容易?

For situations where you may need to take multiple elements from a list in one iteration, an iterator is often a viable solution.对于您可能需要在一次迭代中从列表中获取多个元素的情况,迭代器通常是一种可行的解决方案。 Calling the built-in iter() on any iterable object (lists, strings, dicts, generators) will provide an iterator, which returns objects one at a time, dynamically, and which cannot backtrack .在任何可迭代对象(列表、字符串、字典、生成器iter()上调用内置的iter()将提供一个迭代器,它一次返回一个对象,动态地,并且不能回溯 If you then assign an iterator to a variable and use that variable in a for loop, you can selectively call next() on it yourself to make the loop 'skip' elements:如果然后将迭代器分配给变量并在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'

You'll need to add error handling to this to deal with edge cases, but this should handle your immediate problem.您需要为此添加错误处理以处理边缘情况,但这应该可以解决您的直接问题。

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

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