0

(3987) から (5026) までの範囲のフィールド [Num] の数値の平均値は?

フィールドの下にあるのは、Excel のフィールド [4] です。

**amount       code    quan val     number  Random**
2.11    I[N8U7]:75  184 Blue    2254    Potato
3.13    Z[V0L8]:64  131 Blue    6349    Carrot
4.24    B[Y1U2]:38  56  Blue    4164    Mushrooms
7.32    T[Z7N0]:67  329 Red     2079    Pear
9.1     C[T8C5]:83  344 Blue    1045    Apple
11.17   M[P4J9]:38  267 Blue    1254    Strawberry
2.21    E[S1G7]:62  446 Red     2223    Vanilla
1.41    W[M4M5]:96  8   Red     6745    Juice
2.31    W[P3E1]:24  215 Red     1223    Orange
0.12    E[M5K0]:78  424 Blue    2385    Pineapple
3.91    A[A9M2]:33  367 Red     3354    Grape
3.1     W[N2E2]:70  121 Blue    7716    Watermelon
10.21   J[H2W8]:17  253 Red     1017    Yogurt
5.1     G[K5L5]:08  216 Red     1039    Peppers
1.14    V[Z2C3]:L75 419 Blue    2520    Onions
1.02    Q[I1I2]:20  380 Red     2700    Chocolate
0.19    S[P1X2]:43  133 Blue    3171    Cheese
7.21    Z[B2E3]:46  126 Blue    2971    Ham
10.21   L[F6V1J:28  249 Red     7574    Blueberry
1.02    X[B0N3]:65  243 Blue    3441    Water

次のコードを試しましたが、他に何をすべきかわかりません。前もって感謝します

file=open ('3114644b.csv','r')

def mylist():
    alist=[]
    for line in file:
        field = line.split(',')
        if field[0]=='bid' or field[0]=='leave':
            alist.append(float(field[4]))
    return alist

blist=mylist()
total = 0
count = 0
for num in blist:
    total +=  num
    count += 1

average = total / count

print ("the average of the values)

file.close
4

2 に答える 2

0

cvsこれは、モジュールを使用しないバージョンです。(各タスクに適切なモジュールがある場合は、その使用方法を学習することをお勧めします)

data = []

# This next line closes the file as soon as the block ends (as Martijn suggests)
with open ('3114644b.csv','r') as f:
    for line in f:
        field = line.split(',')
        if field[0] in {'bid', 'leave'}:
            # Note that the 4th column you want to refer to is actually the list
            # list elemnt with index 3, not 4. List indexes start with 0
            data.append(float(field[3]))

# The 'sum()' function is the best choice for your problem as karthirk suggested
# The 'len()' function is a built-in function that returns the number of items
# a list has
average = sum(data)/len(data)

print ("The average of the values is %f" % average)
于 2013-05-10T20:41:43.560 に答える