-2

I'm pretty new to Python although I have learned most the basic's although I need to be able to read from a csv file (which so far works), then append the data from this csv into lists which is working, and the part I am unsure about is using two of these lists and / 120 and * 100

for example the list1 first score is 55 and list2 is 51, I want to merge these together into a list to equal 106 and then add something which can divide then times each one as there is 7 different numbers in each list.

import csv 
list1 = []
list2 = []
with open("scores.csv") as f:
reader = csv.reader(f)
for row in reader:

    list1.append(row[1])
    list2.append(row[2])
print (list1)
print (list2)

OUTPUT

['55', '25', '40', '21', '52', '42', '19']

['51', '36', '50', '39', '53', '33', '40']

EXPECTED OUTPUT (WANTED OUTPUT)

['106', '36', '90', '60', '105', '75', '59']

which then needs to be divided by 120 and * 100 for each one.

1230
  • 3
  • 5

2 Answers2

0

Check out zip.

for a, b in zip(list1, list2):
    # .... do stuff

so for you maybe:

output = [((int(a)+int(b))/120)*100 for a, b in zip(list1, list2)]
Matt R. Wilson
  • 7,268
  • 5
  • 32
  • 48
  • What does a and b mean? – 1230 Oct 11 '16 at 01:12
  • The `zip` function will walk down the two lists yielding values from each until it exhausts the shortest one. In your example, on the first iteration a = '55' and b = '51'. Then on the second iteration a = '25' and b = '36', etc. – Matt R. Wilson Oct 11 '16 at 01:15
  • what would be the best way of making the percentages to whole numbers, as they print with a lot of decimals atm? – 1230 Oct 11 '16 at 01:19
  • Depends on how you want to deal with the lose of data. Casting to an int will just remove the decimal values. You could also round, which pending on which version of py, does different things. – Matt R. Wilson Oct 11 '16 at 01:43
0

Make a new list that takes your desired calculations into account.

>>> list1 = ['55', '25', '40', '21', '52', '42', '19']
>>> list2 = ['51', '36', '50', '39', '53', '33', '40']
>>> result = [(int(x)+int(y))/1.2 for x,y in zip(list1, list2)]
>>> result
[88.33333333333334, 50.833333333333336, 75.0, 50.0, 87.5, 62.5, 49.16666666666667]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97