嵌套循环和夸尔格斯的合法:如何互相调用两个列表? (笛卡尔产品)
我正在尝试重新创建itertools.product
。
我知道如何为此任务创建一个循环,例如:
arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
arr_out = []
for i in arr1:
for i1 in arr2:
final = i, i1
arr_out.append(final)
print(arr_out)
输出:
[(1,5),(1,6),(1,7),(2,5),(2,6),(2,6), (2,7),(3,5),(3,6),(3,7)]
,
但我想知道如何用kwargs
从该函数创建一个函数。 我尝试这样的事情:
arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
def my_cool_product(**kwargs):
arr_out = []
for i in kwargs[0].items():
for i1 in kwargs[1].items():
final = i, i1
arr_out.append(final)
print(my_cool_product(arr1, arr2))
但是它不起作用。
输出:
typeError:my_cool_product()获取0个位置参数,但给出了2个
我不知道如何在嵌套环中调用每个后续kwarg
。 我想获得与第一个示例中相同的输出。
目标是在不导入任何模块的情况下进行操作,例如itertools
,换句话说,从头开始执行此操作。
I'm trying to recreate itertools.product
.
I know how to create a loop for this task, ex.:
arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
arr_out = []
for i in arr1:
for i1 in arr2:
final = i, i1
arr_out.append(final)
print(arr_out)
output:
[(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)]
But I wonder how to create a function from that with kwargs
.
I try something like this:
arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
def my_cool_product(**kwargs):
arr_out = []
for i in kwargs[0].items():
for i1 in kwargs[1].items():
final = i, i1
arr_out.append(final)
print(my_cool_product(arr1, arr2))
But it doesn't work.
output:
TypeError: my_cool_product() takes 0 positional arguments but 2 were given
I don't know how to call each subsequent kwarg
in a nested loop.
I want to get the same output as in the first example.
The goal is to do it without importing any modules, like itertools
, in other words, do it from scratch.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
** Kwargs
不适合像您建议的功能一样。如评论中所链接的那样,
** Kwargs
用于关键字参数函数。在您的情况下,您正在寻找任何数量的未命名列表。假设您在示例函数中所暗示的那样,您只需尝试获得两个阵列:
然后您可以这样使用它:
但是,由于名称
array1
and code> andarray2 < /code>是毫无意义的,使用
*args
将是优选的:有关进一步支持任何数量的列表,请参阅重复问题,因此
*args
和** kwargs
之间的差异。**kwargs
is unfit for a function like the one you're proposing.As linked from in the comments,
**kwargs
is used for variadic keyword argument functions. In your case you're looking for any number of unnamed lists.Let's say there's only 2 arrays you're trying to get the product of, as you imply in your example function:
You may then use it like so:
But since the names
array1
andarray2
are meaningless, using*args
would be preferred:For further supporting any number of lists, please see the duplicate questions, so as for the difference between
*args
and**kwargs
.