繁体   English   中英

bash脚本中的列表积累

[英]list accumulation in bash scripting

如何在 bash 中进行列表累积,在 python 中我可以这样做,但在 bash 中我无法让它工作。

from itertools import accumulate

def list_accumulation(lst):
  output = list(accumulate(map(int,lst)))
return output

list_accumulation([1,2,3]) >>> [1, 3, 6]

由于 bash 的bash不能返回list ,所以我用一串空格分隔的值表示:

#!/bin/bash

list_accumulation() {
    local lst i
    IFS=" " read -r -a lst <<< "$1"
    for (( i = 1; i < ${#lst[@]}; i++ )); do
        (( lst[i] += ${lst[i-1]} ))
    done
    echo "${lst[*]}"
}

list_accumulation "1 2 3"

Output:

1 3 6

正如 tshiono 所说,bash function 无法返回列表。 您可以使用 name-ref 来实现类似的效果:

#!/usr/bin/env bash

list_accumulation(){
    declare -n list_accumulation_internal_list=$1; local i
    for (( i = 1; i < ${#list_accumulation_internal_list[@]}; i++ )); do
        (( list_accumulation_internal_list[i] += ${list_accumulation_internal_list[i-1]} ))
    done
}

list=(1 2 3)
list_accumulation list
echo "${list[@]}"
# 1 3 6

一个很长的变量list_accumulation_internal_list用于避免与外部变量的名称冲突。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM