如何对列表进行排序,如果列表元素重复,请在 tcl 中添加与该元素关联的值
How to sort a list and if the list element repeats, add the values associated with that element in tcl
我的文本文件包含:
Inputs for graph -
0 32
1 0
2 38
3 0
4 74
5 0
6 78
1 47
2 84
我正在尝试读取此文件并存储在另一个文件中,但经过修改,如果第一个元素重复自身,添加与这些元素关联的值并存储为一个元素。
Desired output -
0 32
1 47
2 122
3 0
4 74
5 0
6 78
有人可以指导我完成这个吗?我是通过tcl代码来做的。
假设您的输入和输出都是行文件,每行包含两个简单的整数,其中第一个是您的键,第二个是您的值,您可以很容易地做到这一点。
set data {}
# Read in standard pattern
set f [open "input.txt"]
set rawdata [read $f]
close $f
# For each line...
foreach line [split $rawdata "\n"] {
if {[string trim $line] eq ""} continue; # skip blank lines, just in case
# Split the line into variables
lassign $line key value
# Accumulate, adding up the values for each key
dict incr data $key $value
}
# Sort the result by the keys, type-punning the dict to a list
set data [lsort -stride 2 -index 0 -integer $data]
# Write the data back out
set f [open "output.txt" "w"]
foreach {key value} $data {
puts $f "$key $value"
}
close $f
我的文本文件包含:
Inputs for graph -
0 32
1 0
2 38
3 0
4 74
5 0
6 78
1 47
2 84
我正在尝试读取此文件并存储在另一个文件中,但经过修改,如果第一个元素重复自身,添加与这些元素关联的值并存储为一个元素。
Desired output -
0 32
1 47
2 122
3 0
4 74
5 0
6 78
有人可以指导我完成这个吗?我是通过tcl代码来做的。
假设您的输入和输出都是行文件,每行包含两个简单的整数,其中第一个是您的键,第二个是您的值,您可以很容易地做到这一点。
set data {}
# Read in standard pattern
set f [open "input.txt"]
set rawdata [read $f]
close $f
# For each line...
foreach line [split $rawdata "\n"] {
if {[string trim $line] eq ""} continue; # skip blank lines, just in case
# Split the line into variables
lassign $line key value
# Accumulate, adding up the values for each key
dict incr data $key $value
}
# Sort the result by the keys, type-punning the dict to a list
set data [lsort -stride 2 -index 0 -integer $data]
# Write the data back out
set f [open "output.txt" "w"]
foreach {key value} $data {
puts $f "$key $value"
}
close $f