简体   繁体   English

zip函数可为return语句存储多个输出

[英]zip function to store multiple outputs for a return statement

def somefunction():
    outputs = []
    a = 0
    while a < 100:
        if a%2 == 0:
            b = 2*a + 1
            outputs.append(list(zip(a,b)))
        a += 1
    return outputs

The above code is not what i'm using exactly but produces the same error, why does the above code return: 上面的代码不是我正在使用的,但是会产生相同的错误,为什么上面的代码返回:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: zip argument #1 must support iteration

Is this a particularly efficient way of returning all the items within a function as one? 这是一种将函数中所有项目作为一个对象返回的特别有效的方法吗? If not, what is a better method? 如果没有,什么是更好的方法?

It returns that error because of its exact error message; 由于其确切的错误消息,它返回该错误。 that is, the zip arguments must support iteration. 也就是说, zip参数必须支持迭代。 You just have two numbers that you are trying to "store together". 您只有两个要“存储在一起”的数字。 In that case, I'm assuming what you are looking for is the tuple data type. 在这种情况下,我假设您要查找的是元组数据类型。 Either that or "put them together" with the list data type you already have. 要么将其与现有的列表数据类型“放在一起”,要么将它们“放在一起”。 The zip is entirely unnecessary. 拉链是完全不必要的。 I would suggest reading more about Python's built-in types . 我建议阅读更多有关Python的内置类型的信息

Just get a list of tuples!! 只需获取元组列表!! (or list if you prefer, but since you can't change tuples and you want to return all the outputs, tuples make more sense) (或列出,如果您愿意的话,但是由于您不能更改元组并且要返回所有输出,因此元组更有意义)

def somefunction():
    outputs = []
    a = 0
    while a < 100:
        if a%2 == 0:
            b = 2*a + 1
            tup = (a,b)
            outputs.append(tup)
        a += 1
    return outputs

There is no need to use zip here, zip is for joining two lists together, you only have two integers so you can store them in a tuple and then append the tuple to outputs 这里不需要使用zip ,zip是用于将两个列表连接在一起的,您只有两个整数,因此可以将它们存储在元组中,然后appendappendoutputs

when zip would work for this 何时可以使用zip

Zip would work if you stored all a s in a_list and all b s in b_list . 如果你存储的所有邮编将工作a S IN a_list和所有b S IN b_list Then you could do: 然后,您可以执行以下操作:

outputs.append(zip(a_list,b_list))

this is unnecessary because you can just append a and b together in a tuple to output just like my example. 这是没有必要的,因为您可以append ab一起append到一个元组中以output ,就像我的示例一样。 But that is how it would be done. 但这就是这样做的方式。

You can also use list comprehension in this case: 在这种情况下,您还可以使用列表理解:

def f():
    return [(x, 2*x + 1) for x in range(100) if x%2 == 0]

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

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