在 Mathematica 中选择[nested_list, 条件]
假设我有一个列表:
list=Table[{RandomReal[],RandomReal[],RandomReal[]}, {i,1,100}];
我想根据条件制作一个新列表。现在我知道我应该使用 Select
函数,但我不明白如何定义选择应基于嵌套列表的某些元素的条件。
有人问了类似的问题,我喜欢的答案是:
data = {{0,2},{2,3},{4,3},{5,4},{8,4}};
filtered = Select[data, First[#]>3&];
然而这只有效如果在子列表的第一个元素上设置条件。在我的例子中:
Select[list,0.2>First[#]>0.1&]
给出列表的所有成员,其中 1. 子列表的元素在 0.1 和 0.2 之间。但是,如果我想根据子列表的第二个元素或一般的第 n 个元素进行选择,该怎么办?
另外,元素组合的示例也很好,例如子列表的前 2 个元素的总和小于 0.5。
Let's say I have a list:
list=Table[{RandomReal[],RandomReal[],RandomReal[]}, {i,1,100}];
I'd like to make a new list based on conditions. Now I've seen that I should use the Select
function, but I don't understand how to define the condition where selection should be based on some element of nested list.
Someone asked a similar question and the answer I like was:
data = {{0,2},{2,3},{4,3},{5,4},{8,4}};
filtered = Select[data, First[#]>3&];
However this only works if the condition is set on first element of sublist. In my case:
Select[list,0.2>First[#]>0.1&]
gives all members of the list where 1. element of sublist is between 0.1 and 0.2. But what if I wanted to make selection based on a second element of a sublist, or in general for the nth element?
Also an example with combination of elements would be nice, for example where the sum of first 2 elements of sublist is smaller than 0.5.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,生成列表更容易,因为:
您可以使用
Part
(请参阅文档!!),它相当于[[ ]]
语法,用于获取第n
个元素。例如,这会选择第二个元素大于 0.1 的项目。或者使用
或者
我建议您探索文档中的教程,特别是关于列表操作。
First, generating the list is easier as:
You can use
Part
(see the docs!!), which is equivalent to the[[ ]]
syntax, to take then
th element. E.g. this selects those items which have a second element larger than 0.1.Alternatively use
or
I recommend you explore the tutorials in the documentation, especially the part about list manipulation.