簡體   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