如何在 C# 中创建这个等效列表?

ins*_*iac 0 c# python list-comprehension

在 Python 中,我使用此声明创建了一个最多包含 1000 万个元素的列表,

res = [0, 1] * (N // 2) + [1]
Run Code Online (Sandbox Code Playgroud)

有没有办法在不迭代列表的情况下在 C# 中执行等效操作?我正在尝试这样的事情,

List<int> res = Enumerable.Repeat(0, N).ToList();
Run Code Online (Sandbox Code Playgroud)

但不能完全弄清楚正确的语法。

Adr*_*ian 5

要获取交替使用 0 和 1 的列表,Enumerable.Range然后对结果执行取模:

var N = 10;
var res = Enumerable.Range(0, N).Select(x => x % 2);
Run Code Online (Sandbox Code Playgroud)

输出:

0 1 0 1 0 1 0 1 0 1


如果要重复任意序列,则必须使用Enumerable.Repeat,然后使用SelectMany以下方法组合迭代器:

var res = Enumerable.Repeat(new [] {1, 4, 3}, N).SelectMany(x => x);
Run Code Online (Sandbox Code Playgroud)

输出:

1 4 3 1 4 3 1 4 3 1 4 3 1 4 3 1 4 3 1 4 3 1 4 3 1 4 3 1 4 3

除了数组(或列表),您还可以使用 putEnumerable.Range或任何其他迭代器方法:

var res = Enumerable.Repeat(Enumerable.Range(0,2), N).SelectMany(x => x);
Run Code Online (Sandbox Code Playgroud)

这再次创建了一个交替的 0 和 1 列表。


要在最后添加单个项目,请使用Concat

var res = Enumerable.Range(0, N).Select(x => x % 2).Concat(new [] {1});
Run Code Online (Sandbox Code Playgroud)

输出:

0 1 0 1 0 1 0 1 0 1 1


所以基本上从 Python 到 C#:

  • *Enumerable.Repeat
  • +Enumerable.Concat
  • [a,b,c]new [] {a,b,c}