首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在函数内移动迭代工具产品时,"TypeError:'int‘对象不可迭代“

在函数内移动迭代工具产品时,"TypeError:'int‘对象不可迭代“
EN

Stack Overflow用户
提问于 2016-01-29 16:33:50
回答 1查看 1.5K关注 0票数 2

我试图在函数中移动itertools.product的用法。当我尝试这样做时,我会收到以下错误消息,我不知道为什么:

代码语言:javascript
运行
复制
TypeError: 'int' object is not iterable

代码如下。在main函数中,可以看到函数外部使用的算法,然后可以看到在函数中打包时使用的算法:

代码语言:javascript
运行
复制
#!/usr/bin/env python

import itertools

def main():

    elements_specification = [[10, 20], [30, 40], [50, 60]]

    lists = [list(list_generated) for index, element_specification in enumerate(elements_specification) for list_generated in itertools.product(*elements_specification[:index + 1])]

    for list_configuration in lists:
        print(list_configuration)

    print("---")

    for list_configuration in list_element_combinations_variadic(
        [[10, 20], [30, 40], [50, 60]]
    ):
        print(list_configuration)

def list_element_combinations_variadic(
    elements_specification
    ):
    """
    This function accepts a specification of lists of elements for each place in
    lists in the form of a list, the elements of which are lists of possible
    elements and returns a list of lists corresponding to the combinations of
    elements of the specification with varying numbers of elements.

    For example, the list elements specification [[10, 20], [30, 40], [50, 60]]
    yields the following lists:

    [10]
    [20]
    [10, 30]
    [10, 40]
    [20, 30]
    [20, 40]
    [10, 30, 50]
    [10, 30, 60]
    [10, 40, 50]
    [10, 40, 60]
    [20, 30, 50]
    [20, 30, 60]
    [20, 40, 50]
    [20, 40, 60]
    """
    lists = [list(list_generated) for index, elements_specification in enumerate(elements_specification) for list_generated in itertools.product(*elements_specification[:index + 1])]
    return lists

if __name__ == "__main__":
    main()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-29 16:51:41

基本上,在main方法和另一个方法之间有一个错误。

main中,element_specificationfor中是正确的

代码语言:javascript
运行
复制
for index, element_specification in enumerate(elements_specification)

但是在另一种方法中,elements_specificationfor

代码语言:javascript
运行
复制
for index, elements_specification in enumerate(elements_specification) 

它恰好是该方法的参数名称,所以您要在列表理解中重新分配该参数。

试一试这个

代码语言:javascript
运行
复制
lists = [list(list_generated) for index, element in enumerate(elements_specification) for list_generated in itertools.product(*elements_specification[:index + 1])]
return lists

或者,由于您甚至不需要来自enumerateenumerate,所以只需使用range

代码语言:javascript
运行
复制
lists = [list(list_generated) for index in range(len(elements_specification)) for list_generated in itertools.product(*elements_specification[:index + 1])]
return lists
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35089455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档