在 Mathematica 中选择[nested_list, 条件]

发布于 2024-12-11 14:15:59 字数 662 浏览 5 评论 0原文

假设我有一个列表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

洛阳烟雨空心柳 2024-12-18 14:15:59

首先,生成列表更容易,因为:

list = RandomReal[1, {100, 3}];

您可以使用 Part (请参阅文档!!),它相当于 [[ ]] 语法,用于获取第 n 个元素。例如,这会选择第二个元素大于 0.1 的项目。

Select[list, #[[2]] > 0.1 &]

或者使用

Cases[list, l_ /; l[[2]] > 0.1]

或者

Cases[list, {_, y_, _} /; y > 0.1]

我建议您探索文档中的教程,特别是关于列表操作。

First, generating the list is easier as:

list = RandomReal[1, {100, 3}];

You can use Part (see the docs!!), which is equivalent to the [[ ]] syntax, to take the nth element. E.g. this selects those items which have a second element larger than 0.1.

Select[list, #[[2]] > 0.1 &]

Alternatively use

Cases[list, l_ /; l[[2]] > 0.1]

or

Cases[list, {_, y_, _} /; y > 0.1]

I recommend you explore the tutorials in the documentation, especially the part about list manipulation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文