gpt4 book ai didi

foreach - tcl 中的嵌套 foreach 循环

转载 作者:行者123 更新时间:2023-12-02 16:26:10 33 4
gpt4 key购买 nike

我已经尝试到处寻找,但没有找到一个好的答案。我正在尝试在 tcl 中编写嵌套的 foreach 循环,从两个不同的文本文件中读取行。内部 foreach 循环将完全运行,但外部 foreach 循环将在仅评估文件中的第一行后中断。文本文件看起来像这样(除了大得多)。

输入1.txt:

1
2
3
4
5
6
7
8
9
10

输入2.txt:

a
b
c
d
e
f
g
h
i
j

我的嵌套 foreach 循环的构造如下:

# Open file 1;
set FID1 [open input1.txt r];

# Open file 2
set FID2 [open input2.txt r];

# Open an output file to check the foreach loops;
set outFID [open outputcheck.txt w];

# Nest the foreach loops to read both files
foreach PropLine [split [read $FID1] \n] {
foreach GMprop [split [read $FID2] \n] {
puts $outFID "$PropLine $GMprop";
}
}

close $FID1;
close $FID2;
close $outFID;

我的outputcheck.txt 文件包含

1 a
1 b
1 c
1 d
1 e
1 f
1 g
1 h
1 i
1 j

我通过运行 Windows 7 操作系统的 PC 上的 OpenSEES.exe 可执行文件运行此代码。

预先感谢您的任何见解。

最佳答案

如果您想对 file2 对 file1 的每一行执行某些操作,那么

foreach PropLine [split [read $FID1] \n] {
foreach GMprop [split [read $FID2] \n] {
puts $outFID "$PropLine $GMprop";
}
# jump back to the start of the file, so you can re-read it
# for the next iteration of the outer foreach loop
seek $FID2 0 start
}

但是,看起来您只是想将线条配对,所以

foreach PropLine [split [read -nonewline $FID1] \n] \
GMprop [split [read -nonewline $FID2] \n] \
{
puts $outFID "$PropLine $GMprop";
}

Tcl 允许您同时迭代多个列表,非常方便:http://tcl.tk/man/tcl8.6/TclCmd/foreach.htm

尽管我很想逐行阅读这些文件:

while {true} {
set status1 [gets $FID1 PropLine]
set status2 [gets $FID2 GMprop]
if {$status1 == -1 && $status2 == -1} break
puts $outFID "$PropLine $GMprop"
}

关于foreach - tcl 中的嵌套 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307807/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com