gpt4 book ai didi

python - "TypeError: ' int ' object is not iterable"当在函数内部移动 itertools 产品时

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:48 24 4
gpt4 key购买 nike

我正在尝试在函数内移动 itertools.product 的用法。当我尝试执行此操作时,出现以下错误消息,但我不确定原因:

TypeError: 'int' object is not iterable

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

#!/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()

最佳答案

基本上,您在 main 方法和另一个方法之间存在拼写错误。

main中,您在for中正确地包含了element_specation

for index, element_specification in enumerate(elements_specification)

但是在另一种方法中,您在 for 中有 elements_specification

for index, elements_specification in enumerate(elements_specification) 

这恰好是该方法的参数名称,因此您要在列表理解中重新分配该参数

<小时/>

试试这个

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

或者,由于您甚至不需要 enumerate 中的 element,只需使用 range 即可。

lists = [list(list_generated) for index in range(len(elements_specification)) for list_generated in itertools.product(*elements_specification[:index + 1])]
return lists

关于python - "TypeError: ' int ' object is not iterable"当在函数内部移动 itertools 产品时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35089455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com