【问题标题】:How to find the length of non unique characters in list如何查找列表中非唯一字符的长度
【发布时间】:2015-01-20 17:03:21
【问题描述】:

如何在TCL中查找列表的长度及其非重复/唯一值的值

例如: ABABC ===>预期结果是 唯一字符数为1,其值为C

【问题讨论】:

  • 您可以考虑更改要求非唯一字符的问题标题,而您的问题正文则讨论获取唯一字符的长度跨度>

标签: tcl


【解决方案1】:
set str ABABC
foreach char [split $str ""] {incr count($char)}
foreach key [array names count] {
    if {$count($key) == 1} {
        incr nuniq
        lappend uniq $key
    }
}
puts "$nuniq: [join $uniq ,]"
1: C

代替split,可以用regexp -all -inline {.} $str获取字符串的字符

对于旧的 Tcl,你可以这样做:

proc myincr {varname {step 1}} {
    upvar 1 $varname var
    if {![info exists var]} {
        set var $step
    } else {
        incr var $step
    }
}

并使用myincr 代替incr

【讨论】:

  • 我尝试了这个选项。但是得到错误 msgset str ABABC foreach char [split $str ""] {incr count($char)} foreach key [array names count] { if {$count($ key) == 1} { incr nuniq lappend uniq $key } } puts "$nuniq: [join $uniq ,]" .Getting the following error ==>can't read "count(A)": no such variable (读取要递增的变量值)从“incr count($char)”中调用(“foreach”正文第 1 行)从“foreach char [split $str ""] {incr count($char)}”中调用(文件“t.tcl”第 2 行)
  • @Amirtha 您使用的是 8.5 之前的 Tcl 版本?您应该考虑升级,因为在此之前您不会获得对版本的支持...作为一种解决方法,您可以在incr 之前的一行添加if {![info exist count($char)]} {set count($char) 0},并在第二个循环之前添加set nuniq 0,例如here
【解决方案2】:

另一种方法,

set var "ABCABDF"
foreach v [split $var ""] {
    lappend a $v
}

puts $a

set unique [lsort -unique $a]

set unique_chars ""

foreach item $unique {
    set cnt 0
    foreach i $a {
        if {$item == $i} {
            incr cnt
        }
    }
    if {$cnt == 1} {
        set unique_chars [lappend unique_chars $item]
    }
}

;# To Print Unique Chars
puts $unique_chars

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2017-01-14
    相关资源
    最近更新 更多