簡體   English   中英

用tcl NS-2中的單個數字划分列表

[英]Divide list with the single number in tcl NS-2

我想用一個數字除以整個列表。讓我說我取一個變量$ Content,我想用300個節點除以下面的列表。 所以我接受命令$ Content / 300

  1. $ Content = {1 2 3 4 5} {2 3 4 5 6} {4 5 6 7 8 9} {3 4 6 8 9 0}

結果是輸出{1 2 3 4 5} {2 3 4 5 6} {4 5 6 7 8 9} {3 4 6 8 9 0} / 300,但括號缺失且參數無效。

請告訴我如何將所有列表除以一個數字(300個節點),因為大括號中的每個數字都是一些參數的輸出

請注意,Tcl是一種對空格非常敏感的語言,因此您在$ Content聲明中的右括號和右括號之間需要一個空格。

您可以遍歷$ Content,對於每個子列表,遍歷元素並除以300,以收集結果:

set Content {{1 2 3 4 5} { 2 3 4 5 6} { 4 5 6 7 8 9} {3 4  6 8 9 0}}
# note the spaces ......^............^..............^
set divisor 300
set newContent [list]
foreach sublist $Content {
    set newSublist [list]
    foreach elem $sublist {
        lappend newSublist [expr {$elem * 1.0 / $divisor}]
    }
    lappend newContent $newSublist
}
puts $newContent

輸出是

{0.0033333333333333335 0.006666666666666667 0.01 0.013333333333333334 0.016666666666666666} {0.006666666666666667 0.01 0.013333333333333334 0.016666666666666666 0.02} {0.013333333333333334 0.016666666666666666 0.02 0.023333333333333334 0.02666666666666667 0.03} {0.01 0.013333333333333334 0.02 0.02666666666666667 0.03 0.0}

如果您的Tcl版本是8.6,則可以使用lmap命令來縮短代碼:

set newContent [lmap sublist $Content {
    lmap elem $sublist {expr {$elem * 1.0 / $divisor}}
}]

請注意,我乘以1.0是為了使用浮點除法而不是整數除法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM