用shell和python實現數組的一個例子

目標是把字符串中的值等分爲幾段,取每段固定位置的值python

shell腳本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實現起來簡單多了bash

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
相關文章
相關標籤/搜索