使用 `lmap` 过滤字符串列表 [英] Using `lmap` to filter list of strings

查看:28
本文介绍了使用 `lmap` 过滤字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想从列表中获取所有 5 个字母的单词.

Suppose I want to get all the 5-letter words from a list.

set words {apple banana grape pear peach}
lmap word $words {if {[string length $word] == 5} {expr {"$word"}} else continue}
# ==> apple grape peach

我对 expr {"$word"} 的引用混乱不满意.我希望这会奏效:

I'm not happy with the quoting mess of expr {"$word"}. I was hoping this would work:

lmap word $words {if {[string length $word] == 5} {return $word} else continue}
# ==> apple

从 lmap 主体返回"字符串的优雅方式是什么?

What's an elegant way to "return" a string from the lmap body?

推荐答案

主要的选择是使用 set 或使用 string cat(假设你达到日期).为清楚起见,我将下面的示例分成多行:

The main choices are to use set or to use string cat (assuming you're up to date). I've split the examples below over multiple lines for clarity:

lmap word $words {
    if {[string length $word] != 5} {
        continue
    };
    set word
}

lmap word $words {
    if {[string length $word] == 5} {
        # Requires 8.6.3 or later
        string cat $word
    } else {
        continue
    }
}

这篇关于使用 `lmap` 过滤字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆