Rob*_*cus 4 python bash list-comprehension
是否有可能像python和其他语言一样进行LC,但只使用BASH结构?
我希望能做什么,例如:
function ignoreSpecialFiles()
{
for options in "-L" "-e" "-b" "-c" "-p" "-S" "! -r" "! -w"; do
if [[ $options "$1" -o $options "$2" ]];then
return $IGNORED
fi
done
}
Run Code Online (Sandbox Code Playgroud)
而不是使用这样的代码:
if [[ -L "$1" -o -e "$1" -o -b "$1" -o -c "$1" -o -p "$1" -o -S "$1" -o\
! -r "$1" -o ! -w "$1" ]]
Run Code Online (Sandbox Code Playgroud)
你知道有关模拟LC的任何食谱吗?
一个更具LC的具体例子:
M = [x for x in S if x % 2 == 0] #is python
Run Code Online (Sandbox Code Playgroud)
什么是在bash中做同样的pythonic方式?
for x in S; do if x % 2 == 0;then (HERE MY HEAD EXPLODES) fi done
Run Code Online (Sandbox Code Playgroud)
slo*_*dog 13
如果你眯眼,命令替换中的循环看起来像列表理解.你的第二个例子可以写成:
M=$(for x in $S; do if [ $(( x % 2 )) == 0 ]; then echo $x; fi done)
Run Code Online (Sandbox Code Playgroud)
这是一种半常规格式,用于在bash中使用数组执行LC等效操作:
outarray=()
for x in "${inarray[@]}"; do
if SOMECONDITION; then
outarray+=(SOMEFUNCTIONOFx)
fi
done
Run Code Online (Sandbox Code Playgroud)
这是这种格式的第二个示例:
s=({1..10})
echo "${s[@]}"
# Prints: 1 2 3 4 5 6 7 8 9 10
m=()
for x in "${s[@]}"; do
if (( x % 2 == 0 )); then
m+=($x)
fi
done
echo "${m[@]}"
# Prints: 2 4 6 8 10
Run Code Online (Sandbox Code Playgroud)
这是另一个示例,它的“功能”比较少,但没有条件:
paths=("/path/to/file 1" "/path/somewhere/else" "/this/that/the other" "/here/there/everywhere")
filenames=()
for x in "${paths[@]}"; do
filenames+=( "$(basename "$x")" )
done
printf "'%s' " "${filenames[@]}"
# Prints: 'file 1' 'else' 'the other' 'everywhere'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3209 次 |
| 最近记录: |