0
votes

I have a defined function:

def makeRandomList (values) : 
    length = len(values)
    new_list = []

    for i in range(length) :
        random_num = random.randint(0, length-1)
        new_list.append(values[random_num]*1.0)     #take random samples

    return new_list 

which should just take some samples from an input array values. I have imported such an array as a .csv spreadsheet. Two problems occur:

  1. The array should look like this:

['0', '0']
['1.200408', '29629.0550890999947']
['2.438112', '322162.385751669993']
['3.443816', '511142.915559189975']
['4.500272', '703984.472568470051']
['5.505976', '579295.304300419985']
['6.562432', '703984.472568470051']
['7.568136', '579295.304300419985']
['8.624592', '703984.472568470051']

Which I know through these lines:

import csv
with open('ThruputCSV.csv') as csvfile: 
    readCSV = csv.reader(csvfile, delimiter = ',')
    v = []
    for row in readCSV: 
       print(row) 

When instead of typing print(row) using v.append(row[1]) the resulting v looks like this:

['',
 '0',
 '29629.0550890999947',
 '322162.385751669993',
 '511142.915559189975',
 '703984.472568470051',
 '579295.304300419985',
 '703984.472568470051',
 '579295.304300419985',
 '703984.472568470051']

which is correct exept for the first entry ? Why is the first entry empty?

  1. Now, when running a code (if you're interested, it has kindly been distributed by one user here) , the makeRandomListfunction given v as the values parameter throws an error: can't multiply sequence by non-int of type float

I cannot figure out what is the error - to me v seems to be an array that contains float values. And this should be fine, because the error occurs in this line: new_list.append(values[random_num]*1.0) in which random_num, some integer value, just gives the index of the v array which I want to access. Does this mean I am not allowed to use append with an array that contains float variables?

1

1 Answers

0
votes

You are reading that error wrong... It's not the float value that is an issue

The error is say a 'sequence' cannot be multiplied by a float. Floats and ints can be multiplied with each other. Sequences can NOT be iterated over and multiplied by either floats or ints.

The actual problem is that your array values are strings. Note the ' around each one of them. Those are considered sequences. Convert them to floats and your code will work.

for i in range(length) :
    random_num = random.randint(0, length-1)
    new_list.append(float(values[random_num])*1.0)

Edit: It was pointed out that I originally said sequences cannot be multiplied by floats or ints. The clarify. An array of sequences cannot be ITERATED over AND multiply by an int/float at the same time. If you just multiply the whole sequence by an int it will copy all the elements within the array. Useful knowledge in some cases, however that still does not solve this particular question.