bash 如何将列表分配给关联数组的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29911394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I assign a list to the values of an associative array?
提问by mynameisJEFF
This is basically what I am trying to do: to assign a list to the value of an associative array.
这基本上就是我想要做的:将列表分配给关联数组的值。
#!/usr/local/bin/bash
declare -A params
params[n]=(200 400 600 800)
params[p]=(0.2 0.4)
But I got this error:
但我收到了这个错误:
line 4: params[n]: cannot assign list to array member
line 5: params[p]: cannot assign list to array member
Is there any way to get around this problem ?
有什么办法可以解决这个问题吗?
采纳答案by Cyrus
Try this:
尝试这个:
params=([n]="200 400 600 800" [p]="0.2 0.4")
declare -p params
Output:
输出:
declare -A params='([n]="200 400 600 800" [p]="0.2 0.4" )'
回答by anishsane
Essentially, you want 2 dimensional array:
本质上,您需要二维数组:
1st dimension is de-referenced by 'n' or 'p'.
2nd dimension is de-referenced like a normal array.
第一维由“n”或“p”取消引用。
第二维像普通数组一样被取消引用。
bash
does not support multi-dimensional arrays.
bash
不支持多维数组。
You are left with these options:
您只剩下这些选项:
Use combined index as array index in single-dimensional array.
declare -A params params[n,0]=200 params[n,1]=400 params[n,2]=600 params[n,3]=800 params[p,0]=0.2 params[p,1]=0.4
Use 2 level dereferencing:
declare -A params #Declare 2 normal arrays. array1=(200 400 600 800) array2=(0.2 0.4) #Use the main array to hold the names of these arrays. params[n]=array1[@] params[p]=array2[@] #use the array. printf "%s\n" "${!params[n]}" printf "%s\n" "${!params[p]}"
Good old 2 independent arrays:
param_n=(200 400 600 800) param_p=(0.2 0.4)
使用组合索引作为一维数组中的数组索引。
declare -A params params[n,0]=200 params[n,1]=400 params[n,2]=600 params[n,3]=800 params[p,0]=0.2 params[p,1]=0.4
使用 2 级解引用:
declare -A params #Declare 2 normal arrays. array1=(200 400 600 800) array2=(0.2 0.4) #Use the main array to hold the names of these arrays. params[n]=array1[@] params[p]=array2[@] #use the array. printf "%s\n" "${!params[n]}" printf "%s\n" "${!params[p]}"
好旧的 2 个独立数组:
param_n=(200 400 600 800) param_p=(0.2 0.4)
Using these methods, you can iterate through the arrays even when the values contain spaces.
使用这些方法,即使值包含空格,您也可以遍历数组。
回答by David C. Rankin
Did you mean to store the lists as elements n
and p
in an Associative Array? Like this:
您的意思是列表存储为要素n
和p
关联数组?像这样:
#!/bin/bash
declare -A params
params[n]="200 400 600 800"
params[p]="0.2 0.4"
for i in ${!params[@]}; do
echo "params[$i] = ${params[$i]}"
done
exit 0
Output
输出
$ bash aalist.sh
params[n] = 200 400 600 800
params[p] = 0.2 0.4