我需要對一個隨機的句子進行排序。句子中的每個單詞都有一個索引值。例如設定句子“will2 out4 Things1 work3” Output="Things will work out"
我嘗試使用lsort -index 1 {{will 2} {out 4} {Things 1} {work 3}}
這將提供輸出,因為{Things 1} {will 2} {work 3} {out 4}
我需要幫助來創建子串列并拆分輸入陳述句以使其能夠進行排序。
uj5u.com熱心網友回復:
將單詞決議為其文本和索引部分可以使用regexp(\D匹配一個非數字,并\d匹配一個數字):
regexp {(\D )(\d )} $word -> text index
然后,您可以通過轉換串列或制作輔助串列來進行排序來使用它。
在性能方面,這兩種技術在您的樣本輸入上非常相似(假設明顯轉換為程序),時間差異不到 1%。要么他們真的做同樣多的作業,要么他們在過度努力方面犯了類似的錯誤。
按串列轉換排序
set input "will2 out4 Things1 work3"
set prepared [lmap word $input {
lrange [regexp -inline {(\D )(\d )} $word] 1 end
}]
set sorted [lsort -integer -index 1 $prepared]
set output [lmap pair $sorted {
lindex $pair 0
}]
# Converting that into a one-liner is left as an obvious exercise
使用輔助串列排序
這使用-indices選項 to lsort,它告訴您串列中的值將按什么順序排序;如果您想將該命令應用于其他內容,那就太好了。
set input "will2 out4 Things1 work3"
set texts [set values {}]
foreach word $input {
regexp {(\D )(\d )} $word -> t v
lappend texts $t
lappend values $v
}
set sorted [lsort -indices -integer $values]
set output [lmap idx $sorted {
lindex $texts $idx
}]
uj5u.com熱心網友回復:
您必須首先將您的單詞轉換為可以用 排序的對串列,lsort然后僅提取單詞部分以將它們重新連接成一個句子。這是所謂的decorate-sort-undecorate操作的輕微變化。
#!/usr/bin/env tclsh
set sentence "will2 out4 Things1 work3"
# Turn sentence into a list of pairs of the words and numbers
set pairs [lmap word [split $sentence] {
regexp {([[:alpha:]] )(\d )$} $word -> w n
list $w $n
}]
# Sort based on number much like you're doing in your question
set pairs [lsort -index 1 -integer $pairs]
# And re-join the first elements of the pairs
set sentence [join [lmap pair $pairs { lindex $pair 0 }]]
puts $sentence
如果您在沒有中間變數的情況下一步完成所有操作,則稱為Schwartzian 變換(盡管在這種情況下,我認為可讀性會受到影響):
set sentence [join [lmap pair [lsort -index 1 -integer \
[lmap word [split $sentence] {
regexp {([[:alpha:]] )(\d )$} $word -> w n
list $w $n
}]] { lindex $pair 0 }]]
uj5u.com熱心網友回復:
如果您的句子有九個或更少的單詞,您可以使用 反轉每個單詞lmap,對反轉的單詞進行排序,然后取消反轉。
set sentence "will2 out4 Things1 work3"
set ecnetnes [lmap word $sentence {string reverse $word}]
set sorted_ecnetnes [lsort $ecnetnes]
set sorted_sentence [lmap word $sorted_ecnetnes {string range [string reverse $word] 0 end-1}]
--> Things will work out
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427515.html
