构建一个将多个枚举组合到一个巨大列表中的变量
我想想出最简单的方法来创建一个巨大的列表。
假设我有三个六面骰子,因此它们的值均为 randint(1,6)
。 我想要包含组合这 3 个数字的所有可能方式的一组值,因此它可以是 die1 * die2 + die3 或可以是 die1 ** die3 - die2 等。
我想定义一些变量 Z 等于加法、减法、乘法等。这样,我可以说 die1 Z die2 Z die3,它会给我一个巨大的列表,而无需我将其打印出来。这在Python中可能吗?任何想法将不胜感激。
I'd like to come up with the simplest way possible to create an enormous list.
Let's say I have three six-sided dice, so they'll each have a value of randint(1,6)
.
I want the set of values that encompasses every possible way to combine those 3 numbers, so it could be die1 * die2 + die3 or it could be die1 ** die3 - die2, etc.
I'd like to define some variable Z which equals addition, subtraction, multiplcation, etc. That way, I could say die1 Z die2 Z die3 and it would get me an enormous list, without me having to type it out. Is this possible in Python? Any ideas would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里要知道的关键是您可以将一个函数作为参数传递给另一个函数(或在列表中)。一旦你明白了,这个问题就变得容易解决了。
如果您想要列表理解:
请注意包含“None”,其中通常会发生被零除的情况。
如果你把它分成一个函数,那就更清楚了。它需要两个数字列表和一个运算列表并返回所有结果:
这不会发生被零除的情况。使用类似
results(funcs,die,results(funcs,die,die))
来获取所有结果。这两个结果都有很多重复项,因此根据您实际想要执行的操作,您可能需要一个
set
而不是list
。另外,只是想到了这一点,但根据您计划执行的操作,您可以获取
results
返回生成器:如果您正在处理非常大的结果集,但只想查看逐一列出,这是比构建整个列表更好的选择。
The key thing to know here is that you can pass a function as an argument to another function (or in a list). Once you understand that this problem becomes much easier to solve.
If you want a list comprehension:
Note that contains "None" where a division by zero would have normally occurred.
It's way clearer if you split it out into a function though. It takes two lists of number and a list of operations and returns all results:
This has nothing where a division by zero would have occurred. Use like
results(funcs,die,results(funcs,die,die))
to get all results.Both of these have a lot of duplicates in their outcomes, so depending on what you actually want to do you might want a
set
instead of alist
.Also, just thought of it, but depending on what you're planning to do you could get
results
to return a generator instead:If you're working on really large result sets but only want to look at them one by one this is a better option than building the whole list.
我认为你想问如何最好地重载 python 中的笛卡尔积的运算符。
尝试使用
itertools
中的product
:I think you're trying to ask how to best overload an operator for the Cartesian product in python.
Try using
product
fromitertools
: