Mathematica:确定列表中的所有整数是否都小于一个数字?
Mathematica 有没有办法确定列表中的所有整数是否小于设定值。 例如,如果我想知道列表中的所有数字是否都小于 10:
theList = {1, 2, 3, 10};
magicFunction[theList, 10]; --> returns False
感谢您的帮助。
Is there a way in Mathematica to determine if all the integers in a list are less than a set number. For example if I want to know if all the numbers in a list are less than 10:
theList = {1, 2, 3, 10};
magicFunction[theList, 10]; --> returns False
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看列表的Max 函数,它返回列表中的最大数字。 从那里,您可以检查该值是否小于某个数字。
Look into the Max function for lists, which returns the largest number in the list. From there, you can check if this value is less than a certain number.
在提供我的解决方案之前,让我先评论一下前两个解决方案。 我们将 Joey Robert 的解决方案称为 magicFunction1,将 Eric 的解决方案称为 magicFunction2。
magicFunction1 非常简短而优雅。 我不喜欢的是,如果我有一个非常大的数字列表,并且第一个数字已经大于 10,它仍然会完成所有不需要的最大数字的工作。 这也适用于 magicFunction2
我开发了以下两个解决方案:
并
进行了基准测试,我发现
所以我最好的答案是 magicFunction4,但我仍然不知道为什么它比 magicFunction1 慢。 我也忽略了为什么magicFunction3和magicFunction4的性能差异这么大。
Before offering my solution let me comment the previous two solutions. Lets call Joey Robert's solution magicFunction1 and Eric's solution magicFunction2.
magicFunction1 is very short and elegant. What I don't like about it is that if I have an very large list of numbers and the first one is already bigger than 10 it still will do all the work of figuring out the largest number which is not needed. This also applies to magicFunction2
I developed the following two solutions:
and
Doing a benchmark I found
So my best answer is magicFunction4, but I still don't know why it is slower than magicFunction1. I also ignore why there is such a large performance difference between magicFunction3 and magicFunction4.
使用“Fold”很容易构造这种测试:
短语“(#2 < val)”是每个列表元素(“#2”)的测试。 您可以在这里放置任何您想要的测试,这样您就可以进行比使用 Max 等可列出函数更强大的测试。
' && #1' 然后将当前元素的结果与所有先前元素的结果组合起来。
“True”是基本情况——空列表的结果。
要了解它是如何工作的,您可以传入一些未定义的值并查看表达式扩展为什么:
This kind of test is easy to construct using 'Fold':
The phrase '(#2 < val)' is the test of each list element ('#2'). You could put any test you wanted here, so you can do more powerful tests than you can with a listable function like Max.
The ' && #1' then combines the result for your current element with the result for all prior elements.
And 'True' is the base case -- the result for an empty list.
To see how it works, you can pass in some undefined values and see what the expression expands to: