【问题标题】:How to iterate over x number of lists using zip [duplicate]如何使用 zip 遍历 x 个列表 [重复]
【发布时间】:2015-06-10 23:57:59
【问题描述】:

我有几个需要迭代的列表。我的 zip 函数工作得很好,但是为了让我的代码更灵活,我想知道你将如何使用 zip,但从变量中获取列表的数量?

例如,而不是:

for 1,2,3 in zip(list_1,list_2,list3):
    do something

我们可以做一些类似的事情:

i = 1   
var = number of lists 
zipall = zip(all_my_lists)


for i in range(1,var) in zip(zipall):
    do something

这段代码甚至还没有接近工作,我只是想给出一个我想要做的事情的想法。 任何提示将不胜感激。提前致谢。

更新

感谢到目前为止的提示。看起来使用 * 函数可能会为我完成这项工作。 到目前为止,我正在尝试让我的 zip 语句的前半部分工作:

args = [0,1]
for i in range(*args) in zip(outputlist[0],outputlist[1]):
    print range(*args)

但是以“for”开头的行给了我以下错误:

TypeError: 'bool' object is not iterable

知道我哪里出错了吗?非常感谢到目前为止的帮助。

【问题讨论】:

    标签: python zip


    【解决方案1】:

    您可能对 * 和 ** 感兴趣: What does ** (double star) and * (star) do for parameters?

    • 基本上转换一个列表并将所有内容转换为函数调用中的参数。

    所以:

    myfunc(1,2,3)

    是一样的

    myfunc(*[1,2,3])

    如果您有定义数量的变量和定义的范围,这是没有意义的,但是如果您有可变数量的参数,请使用 * arg 压缩列表并遍历所有这些。

    编辑:你现在做错了一些事情。

    就目前而言,这将修复您的代码,但我怀疑这是您的意图。

    def myfunc(*args):    # this passes an arbitrary number of values
        length = len(args)
        # you cannot add a second "in:, this makes a comparison
        # like 5 > 4, or something, which returns a boolean value
        for i in range(0, length):
            do_something(i)       # this does something to the index
    

    我相信这是你的目标:对所有列表做点什么:

    def myfunc(*args):
        for arg in args:       # grabs each list sequentially
            do_something(arg)
    

    【讨论】:

    • 谢谢,这看起来像是我需要做的。如果您愿意看一下,请用我的进度更新我最初的问题。
    • 已更新。您的新代码中有一些基本语法错误。
    【解决方案2】:

    首先,需要指定实际列表,或者在另一个集合中,以便您可以动态访问它们。假设您有一个列表列表,您可以轻松地执行以下操作:

    all_lists = [range(2),
                 range(2),
                 range(2)]
    
    def zip_test(sentinal=1):
        for items in zip(*all_lists[:sentinal]):
            print items
    
    # demonstration
    >>> zip_test(1)
    (0,)
    (1,)
    >>> zip_test(2)
    (0, 0)
    (1, 1)
    >>> zip_test(3)
    (0, 0, 0)
    (1, 1, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多