Reputation: 1222
I want to read a .csv file containing of two columns. The former represents index names and the latter their corresponding supply. I then want to multiply the supply with some weights represented in the alpha list. However I'm getting the error that
Can't multiply sequence by non-int of type 'float'
in the line where I call writer.write.
From what I've gathered from googling this it is due to that, for instance, [5]*3 creates a list of 3 elements with the value 5, which is what I do not want. I've seen that others has solved it by looping over, in this instance, i in alpha. Is there any other way than to do it in this manner, or how is that done now when I'm not interested in merely one value in every iteration, I'm interested of them all at the same time.
My code is as follows:
#! /usr/bin/python
import csv
import math
writer = open("C:\\Users\\Guda\\Documents\\manipulerat3.csv", "w")
alpha = [0.16,0.13,0.13,0.20]
with open("C:\\Users\\Guda\\Documents\\manipulerat2.csv", "r") as f:
reader = csv.reader(f, delimiter ="\t")
for row in reader:
a = float(row[1])
a = int(math.ceil(a))
writer.write("%s\t\%s\t%s\%s\t%s\n" % (row[0],alpha[0]*a,alpha[1]*a,alpha[2]*a, alpha*alpha[3]))
Upvotes: 0
Views: 61
Reputation: 10092
It looks like what you want to achieve in alpha*alpha[3]
is to multiple all elements by the fourth element. It also further looks like you want to ouput this result as a string at the end (I assume tab-delimited). If this is the case then in place of alpha*alpha[3]
you might want to put:
"\t".join(str(val * alpha[3]) for val in alpha)
Upvotes: 1
Reputation: 5187
try writer.write("%s\t\%s\t%s\%s\t%s\n" % (row[0],alpha[0]*a,alpha[1]*a,alpha[2]*a, alpha[3]*a))
You had a typo in your code which resulted in multiplying the list alpha with alpha[3]. Since alpha[3] is a float, you are getting the error mentioned.
Upvotes: 1