首页 > 技术文章 > 用shell和python实现数组的一个例子

regit 2019-06-24 15:11 原文

目标是把字符串中的值等分为几段,取每段固定位置的值

shell脚本

#!/bin/bash
ele="1 2 3 4 5 6"
n=0
array1=()

for x in $ele
  do
    echo $x
    array1[n]=$x
    echo "the value of array1 is ${array1[$n]}"
    n=$(( $n+1 ))
  done
echo "the number of this array is $n"


item=`expr $n / 3`
key=`expr $item - 1`

for m in $(seq 0 $key)
do
echo "each item's second element value is ${array1[m*3+1]}"
done



echo "the whole ele of array1 is as follows"
echo ${array1[@]}

 

python脚本,很明显python实现起来简单多了

a="1 2 3 4 5 6 7 8"
a=a.replace(" ","")
array1=[]
for x in a:
    array1.append(x)
print(array1)
length=len(array1)
item=length/2
print(item)

i=0
while i < item:
    value = array1[2*i+1]
    print(value)
    i+=1

 

推荐阅读