在 tcl 中对浮点数数组进行排序

问题描述 投票:0回答:1

我刚刚了解了tcl。我正在对整数数组进行排序,但收到错误。我还是不知道如何解决这个问题。

puts [lsort [列表 22,678 11,456 7.6 3,521 8,900 4,987 9,245 10,776]] 结果是: 10,776 11,456 22,678 3,521 4,987 7.6 8,900 9,245 但我希望它们按升序排序: 3,521 4,987 7.6 8,900 9,245 10,776 11,456 22,678 希望大家能帮助我。

arrays list sorting tcl
1个回答
0
投票

在Tcl中,lsort命令用于对列表进行排序。默认情况下,lsort 将每个元素视为字符串,这就是为什么您看到的结果是按字典顺序而不是数字顺序。要按数字对数字进行排序,您需要将 -real 或 -integer 选项与 lsort 一起使用,具体取决于您处理的是实数还是整数。

但是,您的列表中还存在另一个问题:数字中使用逗号。 Tcl 会将它们解释为字符串的一部分,而不是千位分隔符。要正确对数字进行排序,您应该删除逗号。

以下是删除逗号后对列表进行数字排序的方法:

set numbers [list 22678 11456 7.6 3521 8900 4987 9245 10776]
puts [lsort -real $numbers]

如果您想将逗号保留为千位分隔符以用于显示目的,您可以在排序之前将其删除,然后在排序后将它们添加回来。以下是如何做到这一点的示例:

# Original list with commas
set numbers_with_commas [list 22,678 11,456 7.6 3,521 8,900 4,987 9,245 10,776]

# Remove commas for sorting
set numbers [lmap num $numbers_with_commas {regsub -all {,} $num ""}]

# Sort numerically
set sorted_numbers [lsort -real $numbers]

# Add commas back for display
set sorted_numbers_with_commas [lmap num $sorted_numbers {
    # Here you could format the number to have commas, but Tcl doesn't have a built-in way to do this.
    # You would need to write a function to add the commas back in the correct places if needed.
    # For simplicity, this example just returns the number without commas.
    return $num
}]

# Output the result
puts "Sorted numbers: $sorted_numbers_with_commas"

请注意,Tcl 没有内置的方法来用逗号格式化数字作为千位分隔符,因此如果您需要该功能,您必须自己实现它或使用提供此类功能的包

© www.soinside.com 2019 - 2024. All rights reserved.