【问题标题】:Printing values in a formatted way that has different formats depending on value?以根据值具有不同格式的格式化方式打印值?
【发布时间】:2020-10-22 00:45:20
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!这似乎解决了我的问题,并向我介绍了几种新方法,但我可以知道什么是边缘情况吗?如果给定一个极端的最小值或最大值,它看起来不会失败,还是我误解了 python 中边缘情况的含义,或者我可能忽略了你的代码的某些部分?
    • @mhileas (1) 如果 -1 将包含在一对中,例如:在[2, -1, 3, 4] 列表中。 (2) 如果列表的大小错误并且您在一对中间被切断了怎么办,例如[1][2, 3, -1, 4] 等。我使用术语“边缘情况”来指代的不仅仅是边界值问题——它是任何“不太可能”但仍然可能导致代码抛出错误的情况。跨度>
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2011-03-24
    • 2014-11-26
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多