AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[for-loop](coding)

Martin Hope
TheDemonLord
Asked: 2025-04-16 17:30:52 +0800 CST

在 Terraform 中通过 Flatten 创建地图

  • 5

我的问题如下 - 我有一个类似下面的本地代码块。我需要根据这些值创建一个 Map(这些值在多个地方使用)。

locals {
  object = {
    1 = {
      name = "val1"
      keys = ["val1"]
    }
    2 = {
      name = "val2"
      keys = ["val2", "val3", "val4"]
    }
  }
  associations = flatten(
    [
      for obj in local.object : [
        for association_key in obj.keys : {
          "${obj.name}-${association_key}" = {
            key             = obj.name
            association_key = association_key
          }
        }
      ]
    ]
  )
}

当我运行 terraform 计划并输出上述内容时,我得到:

testing = [
      + {
          + val1-val1 = {
              + association_key = "val1"
              + key             = "val1"
            }
        },
      + {
          + val2-val2 = {
              + association_key = "val2"
              + key             = "val2"
            }
        },
      + {
          + val2-val3 = {
              + association_key = "val3"
              + key             = "val2"
            }
        },
      + {
          + val2-val4 = {
              + association_key = "val4"
              + key             = "val2"
            }
        },
    ]

然而我需要得到的东西是这样的:

testing = [
          + val1-val1 = {
              + association_key = "val1"
              + key             = "val1"
            }
          + val2-val2 = {
              + association_key = "val2"
              + key             = "val2"
            }
          + val2-val3 = {
              + association_key = "val3"
              + key             = "val2"
            }
          + val2-val4 = {
              + association_key = "val4"
              + key             = "val2"
            }
    ]

原因是对象的键值有很多重复,并且映射中需要有一个唯一的值。

我已尝试此处的解决方案- 但我无法创建我需要的地图。

for-loop
  • 1 个回答
  • 24 Views
Martin Hope
An5Drama
Asked: 2025-03-07 18:57:03 +0800 CST

非 C 风格 for 循环中“my”变量的作用域

  • 6

最近尝试获取一个“获取匹配括号的索引”的算法。虽然 perl 语言有些问题,但我能理解该算法的含义。

perl 语法并不晦涩,并且可以通过man perl...文档获得很多信息。

my但我对循环行为有点困惑for。man perlsyn说:

如果变量前面带有关键字“my”,则该变量具有词法作用域,因此仅在循环内可见。否则,该变量隐式地位于循环中,并在退出循环时恢复其以前的值。如果变量之前用“my”声明,则它使用该变量而不是全局变量,但它仍然位于循环中。这种隐式本地化仅发生在非 C 样式循环中。

我知道“非 C 风格循环”是指那些不像的循环for (...;...;...){...}。

第一句话可以通过以下方式显示,类似于文档中显示的示例:

$i = 'samba';
# If the variable is preceded with the keyword "my", then it is lexically scoped, and is therefore visible only within the loop.
for (my $i = 1; $i <= 4; $i++) {
  print "$i\n";
}
print "$i\n";
# 1
# 2
# 3
# 4
# samba

但我不明白第二点是什么意思:

$inner = 'samba';
for ($i = 1; $i <= 4; $i++) {
  $inner = $i + 1;
}
print "inner: $inner\n";
# inner: 5

这里所谓的“本地”var$inner似乎修改了外部的var,并且“以前的值”'samba'无法“恢复”。

第三,我们可以对上面的例子做一些小的调整:

$inner = 'samba';
for ($i = 1; $i <= 4; $i++) {
  my $inner = $i + 1;
}
print "inner: $inner\n";
# inner: samba

这对于“而不是全局的”来说是可以正常工作的。

如何理解循环my中的行为for,尤其是上面引用中的第二句?


后续澄清 choroba 的回答提示:当使用正确的“非 C 风格循环”时,第 1 句和第 2 句似乎意味着是否my用于 var 具有相同的效果。但事实并非如此。

sub foo { print "foo: $x\n"; }

$x = 7;
for $x (1 .. 3) {  # Implicit localisation happens here.
  print "$x\n";
  print "global $::x\n";  # Prints 1 .. 3 correspondingly.
  foo(); # Prints 1 .. 3 correspondingly.
}
print $x;  # Prints 7.

$x = 7;
for my $x (1 .. 3) {  # Implicit localisation happens here.
  print "$x\n";
  print "global $::x\n";  # Always prints 7.
  foo(); # Always prints 7.
}
print $x;  # Prints 7.

这只是和之间的区别localmy,仅意味着动态范围与词法范围,正如那里的最佳答案所示,这也在文档中有所说明。

局部变量只是为全局变量(即包变量)赋予临时值。它不会创建局部变量。这称为动态作用域。词汇作用域由我的...完成。

第三个句子示例可以更新:

$i = 'former';
my $i = 'samba';
for $i (1 .. 4) {
  print "$i\n";
}
# > still localized to the loop
# i.e. uses the outside variable value but maybe there are more than one choices. The doc says to choose "my $i = 'samba';".
print "$i\n"; # not use 'former'
# 1
# 2
# 3
# 4
# samba

针对 ikegami 的回答的后续问题:

如果我们添加:

my $x = 7;
for $x (1 .. 3) {  # Implicit localisation happens here.
  print "$x\n";
  print "global $::x\n"; # Prints nothing for $::x.
  foo(); # Prints nothing for $x.
}
print $x;  # Prints 7.

对于上面的sub foo { print "foo: $x\n"; } ...例子,后者$::x 也不能访问后者定义的全局变量$x = 7;。恕我直言,my创建一个新的变量不应该影响那个全局变量。

但是如果我们将后者的 var 定义为our $x = 7;文档中所说的“包(即全​​局)变量的词汇别名”。那么一切都会像以前一样工作。这是什么原因呢?

for-loop
  • 2 个回答
  • 104 Views
Martin Hope
Kit_kat_rin
Asked: 2025-02-07 22:22:02 +0800 CST

传输矩阵时,写一行和两行有什么区别?

  • 6

如果元素的替换写在两行中,则矩阵传输不正确

x=[[i for i in list(map(int,input().split()))] 
   for _ in range(int(input()))]
print("Result:")
for i in range(len(x)):
    for j in range(i,len(x)):
        if i>0:
            j-=1
        x[i][j]=x[j][i]
        x[j][i]=x[i][j]
[print(*i) for i in x]

输入:3 1 2 3 4 5 6 7 8 9

结果:1 4 7 4 5 6 7 6 9

如果元素的替换写在一行中,则矩阵的传输可以正确进行

x=[[i for i in list(map(int,input().split()))] 
   for _ in range(int(input()))]
print("Result:")
for i in range(len(x)):
    for j in range(i,len(x)):
        x[i][j],x[j][i]=x[j][i],x[i][j]
[print(*i) for i in x]

输入:3 1 2 3 4 5 6 7 8 9

结果:1 4 7 2 5 8 3 6 9

为什么会发生这种情况?我不明白其中的区别

for-loop
  • 1 个回答
  • 25 Views
Martin Hope
NLion74
Asked: 2024-10-17 05:01:30 +0800 CST

Rust 特征对象的输入和输出类型不匹配

  • 5

所以我的问题是,我有一个具有以下输入和输出类型的层特征:

pub trait Layer {
    type Input: Dimension;
    type Output: Dimension;
    
    fn forward(&mut self, input: &ArrayBase<OwnedRepr<f32>, Self::Input>) -> ArrayBase<OwnedRepr<f32>, Self::Output>;
}

使用此转发功能:

impl<A: Activation> Layer for DenseLayer<A> {
    type Input = Ix2;
    type Output = Ix2;

    fn forward(&mut self, input: &Array2<f32>) -> Array2<f32> {
        assert_eq!(input.shape()[1], self.weights.shape()[0], "Input width must match weight height.");
        let z = input.dot(&self.weights) + &self.biases;

        self.activation.activate(&z)
    }
}

我有这些,以便我的前向或后向函数可以接受例如 2 维数组,但仍然输出只有 1 维的数组。然后我有一个这种层特征的包装器的实现,我希望通过所有层进行转发:

pub struct NeuralNetwork<'a, L>
where
    L: Layer + 'a,
{
    layers: Vec<L>,
    loss_function: &'a dyn Cost,
}

impl<'a, L> NeuralNetwork<'a, L>
where
    L: Layer + 'a,
{
    pub fn new(layers: Vec<L>, loss_function: &'a dyn Cost) -> Self {
        NeuralNetwork { layers, loss_function }
    }

    pub fn forward(&mut self, input: &ArrayBase<OwnedRepr<f32>, L::Input>) -> ArrayBase<OwnedRepr<f32>, L::Output> {
        let mut output = input.clone();

        // todo fix the layer forward changing input to output
        // causing mismatch in the input and output dimensions of forward
        for layer in &mut self.layers {
            output = layer.forward(&output);
        }

        output
    }
}

现在因为在 for 循环中我首先输入了 input 类型,然后从 layer.forward 接收输出。在下一次迭代中,它采用 output 类型,但 layer.forward 只接受 input 类型。至少我认为这是正在发生的事情。这似乎是一个非常简单的问题,但我真的不确定如何解决这个问题。

编辑1:

可重现的示例:

use ndarray::{Array, Array2, ArrayBase, Dimension, OwnedRepr};

pub trait Layer {
    type Input: Dimension;
    type Output: Dimension;

    fn forward(&mut self, input: &ArrayBase<OwnedRepr<f32>, Self::Input>) -> ArrayBase<OwnedRepr<f32>, Self::Output>;
}

// A Dense Layer struct
pub struct DenseLayer {
    weights: Array2<f32>,
    biases: Array2<f32>,
}

impl DenseLayer {
    pub fn new(input_size: usize, output_size: usize) -> Self {
        let weights = Array::random((input_size, output_size), rand::distributions::Uniform::new(-0.5, 0.5));
        let biases = Array::zeros((1, output_size));
        DenseLayer { weights, biases }
    }
}

impl Layer for DenseLayer {
    type Input = ndarray::Ix2;  // Two-dimensional input
    type Output = ndarray::Ix2; // Two-dimensional output

    fn forward(&mut self, input: &ArrayBase<OwnedRepr<f32>, Self::Input>) -> ArrayBase<OwnedRepr<f32>, Self::Output> {
        assert_eq!(input.shape()[1], self.weights.shape()[0], "Input width must match weight height.");
        let z = input.dot(&self.weights) + &self.biases;
        z // Return the output directly without activation
    }
}

// Neural Network struct
pub struct NeuralNetwork<'a, L>
where
    L: Layer + 'a,
{
    layers: Vec<L>,
}

impl<'a, L> NeuralNetwork<'a, L>
where
    L: Layer + 'a,
{
    pub fn new(layers: Vec<L>) -> Self {
        NeuralNetwork { layers }
    }

    pub fn forward(&mut self, input: &ArrayBase<OwnedRepr<f32>, L::Input>) -> ArrayBase<OwnedRepr<f32>, L::Output> {
        let mut output = input.clone();

        for layer in &mut self.layers {
            output = layer.forward(&output);
        }

        output
    }
}

fn main() {
    // Create a neural network with one Dense Layer
    let mut dense_layer = DenseLayer::new(3, 2);
    let mut nn = NeuralNetwork::new(vec![dense_layer]);

    // Create an example input (1 batch, 3 features)
    let input = Array::from_shape_vec((1, 3), vec![1.0, 2.0, 3.0]).unwrap();
    
    // Forward pass
    let output = nn.forward(&input);
    println!("Output: {:?}", output);
}

for-loop
  • 1 个回答
  • 32 Views
Martin Hope
steve.b
Asked: 2024-09-24 18:00:42 +0800 CST

Delphi 中带有两个计数器的 for 循环

  • 6

我是 Delphi 的新手,因此对于我的问题的平庸我深感抱歉。

我怎样才能在 Delphi 中编写一个for带有两个计数器的循环,就像在 C++ 中那样:

int i, j;
for (i=0, j=0; j<100; i++, j++) {
//do something
}

谢谢

for-loop
  • 2 个回答
  • 92 Views
Martin Hope
محسن عباسی
Asked: 2024-09-02 01:59:03 +0800 CST

如何跟踪您在 Ansible 循环中的位置?

  • 5

我需要在 YAML 文件中以可变的次数写入一些行:

- name: Retry a task until a certain condition is met
  lineinfile:
    path: /root/file
    insertafter: '^listeners:'
    line: 'iteration #iteration_number++'
  retries: {{ a_variable }}
  delay: 10

我还想将每次迭代的执行次数写入文件。类似于以下 for 循环:

for i in {1..a_variable}
  do
    echo "i"
  done

如何追踪循环中的当前位置?

for-loop
  • 2 个回答
  • 71 Views
Martin Hope
mmv456
Asked: 2023-09-08 20:50:31 +0800 CST

如何在 kdb/Q 表中使用带有 if 语句的 for 循环?

  • 5

我是 kdb/Q 的新手。我过去使用过Python,并且正在尝试找出如何使用相当于for 循环的方式遍历kdb 表。我有一个名为 SymbolList 的表,如下所示:

象征 开始日期 结束日期
X 2022.12.09
是 2018.10.27 2022.12.08
Z 2018.04.04 2018.10.26
A 2014.10.05 2018.04.03

我试图将每一行插入到一个不同的函数(已编写)中,该函数会输出一个布尔值,如果该布尔函数的输出返回 True,则循环结束。

谁能帮助我如何做到这一点?提前致谢。

for-loop
  • 1 个回答
  • 38 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve