How can I loop through a Python list and perform math calculations on elements of the list?












1















I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on.



I want to loop through the list and score as follows:



for each pair score that pair 2 beats they receive 2 points, for each they tie 1 point and where they don't beat they get 0 points. The loop then continues and compares each pair's score in the same way. In the example below, pair 2 gets 7 points (beating 3 other pairs and a tie with 1), pair 7 gets 0 points, pair 6 gets 12 points beating every other pair.



My list (generated from an elasticsearch json object) is:



['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']


The python code I have tried (after multiple variations) is:



nsp_mp = 0
ewp_mp = 0
ns_list =
for row in arr["hits"]["hits"]:
nsp = row["_source"]["nsp"]
nsscore = row["_source"]["nsscore"]
ns_list.append(nsp)
ns_list.append(nsscore)

print(ns_list)
x = ns_list[1]
for i in range(6): #number of competing pairs
if x > ns_list[1::2][i]:
nsp_mp = nsp_mp + 2
elif x == ns_list[1::2][i]:
nsp_mp = nsp_mp
else:
nsp_mp = nsp_mp + 1
print(nsp_mp)


which produces:



['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
7


which as per calculation above is correct. But when I try to execute a loop it does not return the correct results.



Maybe the approach is wrong. What is the correct way to do this?



The elasticsearch json object is:



arr = {'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 7, 'max_score': 1.0, 'hits': [{'_index': 'match', '_type': 'score', '_id': 'L_L122cBjpp4O0gQG0qd', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '2', 'ewp': '9', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.896151'}}, {'_index': 'match', '_type': 'score', '_id': 'MPL122cBjpp4O0gQHEog', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '3', 'ewp': '10', 'contract': '4S', 'by': 'N', 'tricks': '10', 'nsscore': '420', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.027631'}}, {'_index': 'match', '_type': 'score', '_id': 'MfL122cBjpp4O0gQHEqk', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.158060'}}, {'_index': 'match', '_type': 'score', '_id': 'MvL122cBjpp4O0gQHUoj', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '5', 'ewp': '12', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '400', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.285460'}}, {'_index': 'match', '_type': 'score', '_id': 'NPL122cBjpp4O0gQHkof', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '7', 'ewp': '14', 'contract': '3NT', 'by': 'S', 'tricks': '8', 'nsscore': '0', 'ewscore': '50', 'timestamp': '2018-12-23T16:45:33.538710'}}, {'_index': 'match', '_type': 'score', '_id': 'LvL122cBjpp4O0gQGkqt', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '1', 'ewp': '8', 'contract': '3NT', 'by': 'N', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.405998'}}, {'_index': 'match', '_type': 'score', '_id': 'M_L122cBjpp4O0gQHUqg', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '6', 'ewp': '13', 'contract': '4S', 'by': 'S', 'tricks': '11', 'nsscore': '480', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.411104'}}]}}









share|improve this question





























    1















    I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on.



    I want to loop through the list and score as follows:



    for each pair score that pair 2 beats they receive 2 points, for each they tie 1 point and where they don't beat they get 0 points. The loop then continues and compares each pair's score in the same way. In the example below, pair 2 gets 7 points (beating 3 other pairs and a tie with 1), pair 7 gets 0 points, pair 6 gets 12 points beating every other pair.



    My list (generated from an elasticsearch json object) is:



    ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']


    The python code I have tried (after multiple variations) is:



    nsp_mp = 0
    ewp_mp = 0
    ns_list =
    for row in arr["hits"]["hits"]:
    nsp = row["_source"]["nsp"]
    nsscore = row["_source"]["nsscore"]
    ns_list.append(nsp)
    ns_list.append(nsscore)

    print(ns_list)
    x = ns_list[1]
    for i in range(6): #number of competing pairs
    if x > ns_list[1::2][i]:
    nsp_mp = nsp_mp + 2
    elif x == ns_list[1::2][i]:
    nsp_mp = nsp_mp
    else:
    nsp_mp = nsp_mp + 1
    print(nsp_mp)


    which produces:



    ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
    7


    which as per calculation above is correct. But when I try to execute a loop it does not return the correct results.



    Maybe the approach is wrong. What is the correct way to do this?



    The elasticsearch json object is:



    arr = {'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 7, 'max_score': 1.0, 'hits': [{'_index': 'match', '_type': 'score', '_id': 'L_L122cBjpp4O0gQG0qd', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '2', 'ewp': '9', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.896151'}}, {'_index': 'match', '_type': 'score', '_id': 'MPL122cBjpp4O0gQHEog', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '3', 'ewp': '10', 'contract': '4S', 'by': 'N', 'tricks': '10', 'nsscore': '420', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.027631'}}, {'_index': 'match', '_type': 'score', '_id': 'MfL122cBjpp4O0gQHEqk', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.158060'}}, {'_index': 'match', '_type': 'score', '_id': 'MvL122cBjpp4O0gQHUoj', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '5', 'ewp': '12', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '400', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.285460'}}, {'_index': 'match', '_type': 'score', '_id': 'NPL122cBjpp4O0gQHkof', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '7', 'ewp': '14', 'contract': '3NT', 'by': 'S', 'tricks': '8', 'nsscore': '0', 'ewscore': '50', 'timestamp': '2018-12-23T16:45:33.538710'}}, {'_index': 'match', '_type': 'score', '_id': 'LvL122cBjpp4O0gQGkqt', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '1', 'ewp': '8', 'contract': '3NT', 'by': 'N', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.405998'}}, {'_index': 'match', '_type': 'score', '_id': 'M_L122cBjpp4O0gQHUqg', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '6', 'ewp': '13', 'contract': '4S', 'by': 'S', 'tricks': '11', 'nsscore': '480', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.411104'}}]}}









    share|improve this question



























      1












      1








      1








      I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on.



      I want to loop through the list and score as follows:



      for each pair score that pair 2 beats they receive 2 points, for each they tie 1 point and where they don't beat they get 0 points. The loop then continues and compares each pair's score in the same way. In the example below, pair 2 gets 7 points (beating 3 other pairs and a tie with 1), pair 7 gets 0 points, pair 6 gets 12 points beating every other pair.



      My list (generated from an elasticsearch json object) is:



      ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']


      The python code I have tried (after multiple variations) is:



      nsp_mp = 0
      ewp_mp = 0
      ns_list =
      for row in arr["hits"]["hits"]:
      nsp = row["_source"]["nsp"]
      nsscore = row["_source"]["nsscore"]
      ns_list.append(nsp)
      ns_list.append(nsscore)

      print(ns_list)
      x = ns_list[1]
      for i in range(6): #number of competing pairs
      if x > ns_list[1::2][i]:
      nsp_mp = nsp_mp + 2
      elif x == ns_list[1::2][i]:
      nsp_mp = nsp_mp
      else:
      nsp_mp = nsp_mp + 1
      print(nsp_mp)


      which produces:



      ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
      7


      which as per calculation above is correct. But when I try to execute a loop it does not return the correct results.



      Maybe the approach is wrong. What is the correct way to do this?



      The elasticsearch json object is:



      arr = {'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 7, 'max_score': 1.0, 'hits': [{'_index': 'match', '_type': 'score', '_id': 'L_L122cBjpp4O0gQG0qd', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '2', 'ewp': '9', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.896151'}}, {'_index': 'match', '_type': 'score', '_id': 'MPL122cBjpp4O0gQHEog', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '3', 'ewp': '10', 'contract': '4S', 'by': 'N', 'tricks': '10', 'nsscore': '420', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.027631'}}, {'_index': 'match', '_type': 'score', '_id': 'MfL122cBjpp4O0gQHEqk', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.158060'}}, {'_index': 'match', '_type': 'score', '_id': 'MvL122cBjpp4O0gQHUoj', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '5', 'ewp': '12', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '400', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.285460'}}, {'_index': 'match', '_type': 'score', '_id': 'NPL122cBjpp4O0gQHkof', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '7', 'ewp': '14', 'contract': '3NT', 'by': 'S', 'tricks': '8', 'nsscore': '0', 'ewscore': '50', 'timestamp': '2018-12-23T16:45:33.538710'}}, {'_index': 'match', '_type': 'score', '_id': 'LvL122cBjpp4O0gQGkqt', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '1', 'ewp': '8', 'contract': '3NT', 'by': 'N', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.405998'}}, {'_index': 'match', '_type': 'score', '_id': 'M_L122cBjpp4O0gQHUqg', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '6', 'ewp': '13', 'contract': '4S', 'by': 'S', 'tricks': '11', 'nsscore': '480', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.411104'}}]}}









      share|improve this question
















      I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on.



      I want to loop through the list and score as follows:



      for each pair score that pair 2 beats they receive 2 points, for each they tie 1 point and where they don't beat they get 0 points. The loop then continues and compares each pair's score in the same way. In the example below, pair 2 gets 7 points (beating 3 other pairs and a tie with 1), pair 7 gets 0 points, pair 6 gets 12 points beating every other pair.



      My list (generated from an elasticsearch json object) is:



      ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']


      The python code I have tried (after multiple variations) is:



      nsp_mp = 0
      ewp_mp = 0
      ns_list =
      for row in arr["hits"]["hits"]:
      nsp = row["_source"]["nsp"]
      nsscore = row["_source"]["nsscore"]
      ns_list.append(nsp)
      ns_list.append(nsscore)

      print(ns_list)
      x = ns_list[1]
      for i in range(6): #number of competing pairs
      if x > ns_list[1::2][i]:
      nsp_mp = nsp_mp + 2
      elif x == ns_list[1::2][i]:
      nsp_mp = nsp_mp
      else:
      nsp_mp = nsp_mp + 1
      print(nsp_mp)


      which produces:



      ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
      7


      which as per calculation above is correct. But when I try to execute a loop it does not return the correct results.



      Maybe the approach is wrong. What is the correct way to do this?



      The elasticsearch json object is:



      arr = {'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 7, 'max_score': 1.0, 'hits': [{'_index': 'match', '_type': 'score', '_id': 'L_L122cBjpp4O0gQG0qd', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '2', 'ewp': '9', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.896151'}}, {'_index': 'match', '_type': 'score', '_id': 'MPL122cBjpp4O0gQHEog', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '3', 'ewp': '10', 'contract': '4S', 'by': 'N', 'tricks': '10', 'nsscore': '420', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.027631'}}, {'_index': 'match', '_type': 'score', '_id': 'MfL122cBjpp4O0gQHEqk', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.158060'}}, {'_index': 'match', '_type': 'score', '_id': 'MvL122cBjpp4O0gQHUoj', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '5', 'ewp': '12', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '400', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.285460'}}, {'_index': 'match', '_type': 'score', '_id': 'NPL122cBjpp4O0gQHkof', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '7', 'ewp': '14', 'contract': '3NT', 'by': 'S', 'tricks': '8', 'nsscore': '0', 'ewscore': '50', 'timestamp': '2018-12-23T16:45:33.538710'}}, {'_index': 'match', '_type': 'score', '_id': 'LvL122cBjpp4O0gQGkqt', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '1', 'ewp': '8', 'contract': '3NT', 'by': 'N', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.405998'}}, {'_index': 'match', '_type': 'score', '_id': 'M_L122cBjpp4O0gQHUqg', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '6', 'ewp': '13', 'contract': '4S', 'by': 'S', 'tricks': '11', 'nsscore': '480', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.411104'}}]}}






      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 2 at 12:07









      Tagc

      5,11553071




      5,11553071










      asked Jan 2 at 11:55









      user1903663user1903663

      5241931




      5241931
























          4 Answers
          4






          active

          oldest

          votes


















          1














          List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.




          Note there are a few minor mistakes in listings below - to make sure
          I'm not solving someone's homework for free. I also realize this is
          not the most efficient way of doing so.




          Try with dicts:



          1) convert elasticsearch json you have to a dict with a better structure:



          scores = {}
          for row in arr["hits"]["hits"]:
          nsp = row["_source"]["nsp"]
          nsscore = row["_source"]["nsscore"]
          scores[nsp] = nsscore


          This will give you something like this:



          {'1': '430',
          '2': '430',
          '3': '420',
          '4': '460',
          '5': '400',
          '6': '480',
          '7': '0'}


          2) write a function to calculate pair score:



          def calculate_score(pair, scores):
          score = 0
          for p in scores:
          if p == pair:
          continue
          if scores[p] < scores[pair]:
          score += 2 # win
          elif scores[p] == scores[pair]:
          score += 1
          return score


          This should give you something like this:



          In [13]: calculate_score('1', scores)
          Out[13]: 7

          In [14]: calculate_score('7', scores)
          Out[14]: 0


          3) loop over all pairs, calculating scores. I'll leave this as exercise.






          share|improve this answer
























          • awesome, thank you! It works perfectly.

            – user1903663
            Jan 2 at 13:13











          • the complete picture is: board_num = arr["hits"]["total"] top = (board_num - 1) * 2 result_score = {} for row in arr["hits"]["hits"]: nsp = row["_source"]["nsp"] ewp = row["_source"]["ewp"] res = calculate_score(nsp, scores) ew_mp_score = top - res result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score}) print(result_score)

            – user1903663
            Jan 2 at 13:39



















          0














          The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to int, so that the comparison is correct. In your code, you get for ties 0 points.
          Instead of having a list, with flattend pairs, you should use tuple pairs.



          ns_list = 
          for row in arr["hits"]["hits"]:
          nsp = int(row["_source"]["nsp"])
          nsscore = int(row["_source"]["nsscore"])
          ns_list.append((nsp, nsscore))

          print(ns_list)
          x = ns_list[0][1]
          nsp_mp = 0
          for nsp, nsscore in ns_list:
          if x > nsscore:
          nsp_mp += 2
          elif x == nsscore:
          nsp_mp += 1
          print(nsp_mp)





          share|improve this answer
























          • thank you very much, this works too.

            – user1903663
            Jan 2 at 13:41











          • the reason it is /was 7 is because one of the scores belongs to each pair so the comparison should be with the other 6.

            – user1903663
            Jan 2 at 13:57



















          0














          So we can do it like so:



          import itertools

          d = [(i['_source']['nsp'], i['_source']['nsscore']) for i in arr['hits']['hits']]

          d

          [('2', '430'),
          ('3', '420'),
          ('4', '460'),
          ('5', '400'),
          ('7', '0'),
          ('1', '430'),
          ('6', '480')]

          c = itertools.combinations(d, 2)

          counts = {}
          for tup in c:
          p1, p2 = tup
          if not counts.get(p1[0]):
          counts[p1[0]] = 0
          if int(p1[1]) > int(p2[1]):
          counts[p1[0]] += 1

          counts

          {'2': 3, '3': 2, '4': 3, '5': 1, '7': 0, '1': 0}





          share|improve this answer
























          • I need to study how this can be applied, thank you. I will comment again once I have experimented with it.

            – user1903663
            Jan 2 at 13:14











          • If you use combinations (which is a good idea), you also need to test int(p1[1]) < int(p2[1]) to get the correct results (e.g. team 1 has two wins, and the most winning team 6 is not even in your result).

            – myrmica
            Jan 2 at 14:09











          • I am unsure what the counts dictionary elements are.

            – user1903663
            Jan 2 at 16:41



















          0














          I first convert the list of your score to a dictionary object using itertools, then iterating through each key, and for each key, compare the values available in the list
          and add accordingly the score you provided and since in this approach you will always add the value 1 because you will always compare it with itself so at end i decrease 1 from the final score there may be a better approach for this



          ls = ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
          d = dict(itertools.zip_longest(*[iter(ls)] * 2, fillvalue=""))
          values= d.values()
          for item in d.keys():
          score=0
          for i in values:
          if d[item]>i:
          score+=2
          elif d[item]==i:
          score+=1
          else:
          pass
          print(item,":",score-1)


          Output:



          2 : 7
          3 : 4
          4 : 10
          5 : 2
          7 : 0
          1 : 7
          6 : 12





          share|improve this answer



















          • 1





            also wonderful, thank you. So many cool answers to this problem which I have been struggling with for days. Thank you.

            – user1903663
            Jan 2 at 14:20






          • 1





            The zipping part is clever, took me a moment to understand. Now I see it's in the itertools recipes as grouper. A simple builtin zip would work as well in this case.

            – myrmica
            Jan 2 at 14:59











          • @myrmica Yes, actually i also don't know this before, but while searching for the solution how to convert list into dict i found that response. and learned new thing with it

            – Gaurav
            Jan 2 at 16:15











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005909%2fhow-can-i-loop-through-a-python-list-and-perform-math-calculations-on-elements-o%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.




          Note there are a few minor mistakes in listings below - to make sure
          I'm not solving someone's homework for free. I also realize this is
          not the most efficient way of doing so.




          Try with dicts:



          1) convert elasticsearch json you have to a dict with a better structure:



          scores = {}
          for row in arr["hits"]["hits"]:
          nsp = row["_source"]["nsp"]
          nsscore = row["_source"]["nsscore"]
          scores[nsp] = nsscore


          This will give you something like this:



          {'1': '430',
          '2': '430',
          '3': '420',
          '4': '460',
          '5': '400',
          '6': '480',
          '7': '0'}


          2) write a function to calculate pair score:



          def calculate_score(pair, scores):
          score = 0
          for p in scores:
          if p == pair:
          continue
          if scores[p] < scores[pair]:
          score += 2 # win
          elif scores[p] == scores[pair]:
          score += 1
          return score


          This should give you something like this:



          In [13]: calculate_score('1', scores)
          Out[13]: 7

          In [14]: calculate_score('7', scores)
          Out[14]: 0


          3) loop over all pairs, calculating scores. I'll leave this as exercise.






          share|improve this answer
























          • awesome, thank you! It works perfectly.

            – user1903663
            Jan 2 at 13:13











          • the complete picture is: board_num = arr["hits"]["total"] top = (board_num - 1) * 2 result_score = {} for row in arr["hits"]["hits"]: nsp = row["_source"]["nsp"] ewp = row["_source"]["ewp"] res = calculate_score(nsp, scores) ew_mp_score = top - res result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score}) print(result_score)

            – user1903663
            Jan 2 at 13:39
















          1














          List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.




          Note there are a few minor mistakes in listings below - to make sure
          I'm not solving someone's homework for free. I also realize this is
          not the most efficient way of doing so.




          Try with dicts:



          1) convert elasticsearch json you have to a dict with a better structure:



          scores = {}
          for row in arr["hits"]["hits"]:
          nsp = row["_source"]["nsp"]
          nsscore = row["_source"]["nsscore"]
          scores[nsp] = nsscore


          This will give you something like this:



          {'1': '430',
          '2': '430',
          '3': '420',
          '4': '460',
          '5': '400',
          '6': '480',
          '7': '0'}


          2) write a function to calculate pair score:



          def calculate_score(pair, scores):
          score = 0
          for p in scores:
          if p == pair:
          continue
          if scores[p] < scores[pair]:
          score += 2 # win
          elif scores[p] == scores[pair]:
          score += 1
          return score


          This should give you something like this:



          In [13]: calculate_score('1', scores)
          Out[13]: 7

          In [14]: calculate_score('7', scores)
          Out[14]: 0


          3) loop over all pairs, calculating scores. I'll leave this as exercise.






          share|improve this answer
























          • awesome, thank you! It works perfectly.

            – user1903663
            Jan 2 at 13:13











          • the complete picture is: board_num = arr["hits"]["total"] top = (board_num - 1) * 2 result_score = {} for row in arr["hits"]["hits"]: nsp = row["_source"]["nsp"] ewp = row["_source"]["ewp"] res = calculate_score(nsp, scores) ew_mp_score = top - res result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score}) print(result_score)

            – user1903663
            Jan 2 at 13:39














          1












          1








          1







          List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.




          Note there are a few minor mistakes in listings below - to make sure
          I'm not solving someone's homework for free. I also realize this is
          not the most efficient way of doing so.




          Try with dicts:



          1) convert elasticsearch json you have to a dict with a better structure:



          scores = {}
          for row in arr["hits"]["hits"]:
          nsp = row["_source"]["nsp"]
          nsscore = row["_source"]["nsscore"]
          scores[nsp] = nsscore


          This will give you something like this:



          {'1': '430',
          '2': '430',
          '3': '420',
          '4': '460',
          '5': '400',
          '6': '480',
          '7': '0'}


          2) write a function to calculate pair score:



          def calculate_score(pair, scores):
          score = 0
          for p in scores:
          if p == pair:
          continue
          if scores[p] < scores[pair]:
          score += 2 # win
          elif scores[p] == scores[pair]:
          score += 1
          return score


          This should give you something like this:



          In [13]: calculate_score('1', scores)
          Out[13]: 7

          In [14]: calculate_score('7', scores)
          Out[14]: 0


          3) loop over all pairs, calculating scores. I'll leave this as exercise.






          share|improve this answer













          List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.




          Note there are a few minor mistakes in listings below - to make sure
          I'm not solving someone's homework for free. I also realize this is
          not the most efficient way of doing so.




          Try with dicts:



          1) convert elasticsearch json you have to a dict with a better structure:



          scores = {}
          for row in arr["hits"]["hits"]:
          nsp = row["_source"]["nsp"]
          nsscore = row["_source"]["nsscore"]
          scores[nsp] = nsscore


          This will give you something like this:



          {'1': '430',
          '2': '430',
          '3': '420',
          '4': '460',
          '5': '400',
          '6': '480',
          '7': '0'}


          2) write a function to calculate pair score:



          def calculate_score(pair, scores):
          score = 0
          for p in scores:
          if p == pair:
          continue
          if scores[p] < scores[pair]:
          score += 2 # win
          elif scores[p] == scores[pair]:
          score += 1
          return score


          This should give you something like this:



          In [13]: calculate_score('1', scores)
          Out[13]: 7

          In [14]: calculate_score('7', scores)
          Out[14]: 0


          3) loop over all pairs, calculating scores. I'll leave this as exercise.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 12:17









          rvsrvs

          952821




          952821













          • awesome, thank you! It works perfectly.

            – user1903663
            Jan 2 at 13:13











          • the complete picture is: board_num = arr["hits"]["total"] top = (board_num - 1) * 2 result_score = {} for row in arr["hits"]["hits"]: nsp = row["_source"]["nsp"] ewp = row["_source"]["ewp"] res = calculate_score(nsp, scores) ew_mp_score = top - res result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score}) print(result_score)

            – user1903663
            Jan 2 at 13:39



















          • awesome, thank you! It works perfectly.

            – user1903663
            Jan 2 at 13:13











          • the complete picture is: board_num = arr["hits"]["total"] top = (board_num - 1) * 2 result_score = {} for row in arr["hits"]["hits"]: nsp = row["_source"]["nsp"] ewp = row["_source"]["ewp"] res = calculate_score(nsp, scores) ew_mp_score = top - res result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score}) print(result_score)

            – user1903663
            Jan 2 at 13:39

















          awesome, thank you! It works perfectly.

          – user1903663
          Jan 2 at 13:13





          awesome, thank you! It works perfectly.

          – user1903663
          Jan 2 at 13:13













          the complete picture is: board_num = arr["hits"]["total"] top = (board_num - 1) * 2 result_score = {} for row in arr["hits"]["hits"]: nsp = row["_source"]["nsp"] ewp = row["_source"]["ewp"] res = calculate_score(nsp, scores) ew_mp_score = top - res result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score}) print(result_score)

          – user1903663
          Jan 2 at 13:39





          the complete picture is: board_num = arr["hits"]["total"] top = (board_num - 1) * 2 result_score = {} for row in arr["hits"]["hits"]: nsp = row["_source"]["nsp"] ewp = row["_source"]["ewp"] res = calculate_score(nsp, scores) ew_mp_score = top - res result_score.update({'nsp':nsp, 'ns_mp_score': res, 'ewp': ewp, 'ew_mp_score': ew_mp_score}) print(result_score)

          – user1903663
          Jan 2 at 13:39













          0














          The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to int, so that the comparison is correct. In your code, you get for ties 0 points.
          Instead of having a list, with flattend pairs, you should use tuple pairs.



          ns_list = 
          for row in arr["hits"]["hits"]:
          nsp = int(row["_source"]["nsp"])
          nsscore = int(row["_source"]["nsscore"])
          ns_list.append((nsp, nsscore))

          print(ns_list)
          x = ns_list[0][1]
          nsp_mp = 0
          for nsp, nsscore in ns_list:
          if x > nsscore:
          nsp_mp += 2
          elif x == nsscore:
          nsp_mp += 1
          print(nsp_mp)





          share|improve this answer
























          • thank you very much, this works too.

            – user1903663
            Jan 2 at 13:41











          • the reason it is /was 7 is because one of the scores belongs to each pair so the comparison should be with the other 6.

            – user1903663
            Jan 2 at 13:57
















          0














          The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to int, so that the comparison is correct. In your code, you get for ties 0 points.
          Instead of having a list, with flattend pairs, you should use tuple pairs.



          ns_list = 
          for row in arr["hits"]["hits"]:
          nsp = int(row["_source"]["nsp"])
          nsscore = int(row["_source"]["nsscore"])
          ns_list.append((nsp, nsscore))

          print(ns_list)
          x = ns_list[0][1]
          nsp_mp = 0
          for nsp, nsscore in ns_list:
          if x > nsscore:
          nsp_mp += 2
          elif x == nsscore:
          nsp_mp += 1
          print(nsp_mp)





          share|improve this answer
























          • thank you very much, this works too.

            – user1903663
            Jan 2 at 13:41











          • the reason it is /was 7 is because one of the scores belongs to each pair so the comparison should be with the other 6.

            – user1903663
            Jan 2 at 13:57














          0












          0








          0







          The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to int, so that the comparison is correct. In your code, you get for ties 0 points.
          Instead of having a list, with flattend pairs, you should use tuple pairs.



          ns_list = 
          for row in arr["hits"]["hits"]:
          nsp = int(row["_source"]["nsp"])
          nsscore = int(row["_source"]["nsscore"])
          ns_list.append((nsp, nsscore))

          print(ns_list)
          x = ns_list[0][1]
          nsp_mp = 0
          for nsp, nsscore in ns_list:
          if x > nsscore:
          nsp_mp += 2
          elif x == nsscore:
          nsp_mp += 1
          print(nsp_mp)





          share|improve this answer













          The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to int, so that the comparison is correct. In your code, you get for ties 0 points.
          Instead of having a list, with flattend pairs, you should use tuple pairs.



          ns_list = 
          for row in arr["hits"]["hits"]:
          nsp = int(row["_source"]["nsp"])
          nsscore = int(row["_source"]["nsscore"])
          ns_list.append((nsp, nsscore))

          print(ns_list)
          x = ns_list[0][1]
          nsp_mp = 0
          for nsp, nsscore in ns_list:
          if x > nsscore:
          nsp_mp += 2
          elif x == nsscore:
          nsp_mp += 1
          print(nsp_mp)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 12:16









          DanielDaniel

          32.6k42961




          32.6k42961













          • thank you very much, this works too.

            – user1903663
            Jan 2 at 13:41











          • the reason it is /was 7 is because one of the scores belongs to each pair so the comparison should be with the other 6.

            – user1903663
            Jan 2 at 13:57



















          • thank you very much, this works too.

            – user1903663
            Jan 2 at 13:41











          • the reason it is /was 7 is because one of the scores belongs to each pair so the comparison should be with the other 6.

            – user1903663
            Jan 2 at 13:57

















          thank you very much, this works too.

          – user1903663
          Jan 2 at 13:41





          thank you very much, this works too.

          – user1903663
          Jan 2 at 13:41













          the reason it is /was 7 is because one of the scores belongs to each pair so the comparison should be with the other 6.

          – user1903663
          Jan 2 at 13:57





          the reason it is /was 7 is because one of the scores belongs to each pair so the comparison should be with the other 6.

          – user1903663
          Jan 2 at 13:57











          0














          So we can do it like so:



          import itertools

          d = [(i['_source']['nsp'], i['_source']['nsscore']) for i in arr['hits']['hits']]

          d

          [('2', '430'),
          ('3', '420'),
          ('4', '460'),
          ('5', '400'),
          ('7', '0'),
          ('1', '430'),
          ('6', '480')]

          c = itertools.combinations(d, 2)

          counts = {}
          for tup in c:
          p1, p2 = tup
          if not counts.get(p1[0]):
          counts[p1[0]] = 0
          if int(p1[1]) > int(p2[1]):
          counts[p1[0]] += 1

          counts

          {'2': 3, '3': 2, '4': 3, '5': 1, '7': 0, '1': 0}





          share|improve this answer
























          • I need to study how this can be applied, thank you. I will comment again once I have experimented with it.

            – user1903663
            Jan 2 at 13:14











          • If you use combinations (which is a good idea), you also need to test int(p1[1]) < int(p2[1]) to get the correct results (e.g. team 1 has two wins, and the most winning team 6 is not even in your result).

            – myrmica
            Jan 2 at 14:09











          • I am unsure what the counts dictionary elements are.

            – user1903663
            Jan 2 at 16:41
















          0














          So we can do it like so:



          import itertools

          d = [(i['_source']['nsp'], i['_source']['nsscore']) for i in arr['hits']['hits']]

          d

          [('2', '430'),
          ('3', '420'),
          ('4', '460'),
          ('5', '400'),
          ('7', '0'),
          ('1', '430'),
          ('6', '480')]

          c = itertools.combinations(d, 2)

          counts = {}
          for tup in c:
          p1, p2 = tup
          if not counts.get(p1[0]):
          counts[p1[0]] = 0
          if int(p1[1]) > int(p2[1]):
          counts[p1[0]] += 1

          counts

          {'2': 3, '3': 2, '4': 3, '5': 1, '7': 0, '1': 0}





          share|improve this answer
























          • I need to study how this can be applied, thank you. I will comment again once I have experimented with it.

            – user1903663
            Jan 2 at 13:14











          • If you use combinations (which is a good idea), you also need to test int(p1[1]) < int(p2[1]) to get the correct results (e.g. team 1 has two wins, and the most winning team 6 is not even in your result).

            – myrmica
            Jan 2 at 14:09











          • I am unsure what the counts dictionary elements are.

            – user1903663
            Jan 2 at 16:41














          0












          0








          0







          So we can do it like so:



          import itertools

          d = [(i['_source']['nsp'], i['_source']['nsscore']) for i in arr['hits']['hits']]

          d

          [('2', '430'),
          ('3', '420'),
          ('4', '460'),
          ('5', '400'),
          ('7', '0'),
          ('1', '430'),
          ('6', '480')]

          c = itertools.combinations(d, 2)

          counts = {}
          for tup in c:
          p1, p2 = tup
          if not counts.get(p1[0]):
          counts[p1[0]] = 0
          if int(p1[1]) > int(p2[1]):
          counts[p1[0]] += 1

          counts

          {'2': 3, '3': 2, '4': 3, '5': 1, '7': 0, '1': 0}





          share|improve this answer













          So we can do it like so:



          import itertools

          d = [(i['_source']['nsp'], i['_source']['nsscore']) for i in arr['hits']['hits']]

          d

          [('2', '430'),
          ('3', '420'),
          ('4', '460'),
          ('5', '400'),
          ('7', '0'),
          ('1', '430'),
          ('6', '480')]

          c = itertools.combinations(d, 2)

          counts = {}
          for tup in c:
          p1, p2 = tup
          if not counts.get(p1[0]):
          counts[p1[0]] = 0
          if int(p1[1]) > int(p2[1]):
          counts[p1[0]] += 1

          counts

          {'2': 3, '3': 2, '4': 3, '5': 1, '7': 0, '1': 0}






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 12:20









          aws_apprenticeaws_apprentice

          3,6681723




          3,6681723













          • I need to study how this can be applied, thank you. I will comment again once I have experimented with it.

            – user1903663
            Jan 2 at 13:14











          • If you use combinations (which is a good idea), you also need to test int(p1[1]) < int(p2[1]) to get the correct results (e.g. team 1 has two wins, and the most winning team 6 is not even in your result).

            – myrmica
            Jan 2 at 14:09











          • I am unsure what the counts dictionary elements are.

            – user1903663
            Jan 2 at 16:41



















          • I need to study how this can be applied, thank you. I will comment again once I have experimented with it.

            – user1903663
            Jan 2 at 13:14











          • If you use combinations (which is a good idea), you also need to test int(p1[1]) < int(p2[1]) to get the correct results (e.g. team 1 has two wins, and the most winning team 6 is not even in your result).

            – myrmica
            Jan 2 at 14:09











          • I am unsure what the counts dictionary elements are.

            – user1903663
            Jan 2 at 16:41

















          I need to study how this can be applied, thank you. I will comment again once I have experimented with it.

          – user1903663
          Jan 2 at 13:14





          I need to study how this can be applied, thank you. I will comment again once I have experimented with it.

          – user1903663
          Jan 2 at 13:14













          If you use combinations (which is a good idea), you also need to test int(p1[1]) < int(p2[1]) to get the correct results (e.g. team 1 has two wins, and the most winning team 6 is not even in your result).

          – myrmica
          Jan 2 at 14:09





          If you use combinations (which is a good idea), you also need to test int(p1[1]) < int(p2[1]) to get the correct results (e.g. team 1 has two wins, and the most winning team 6 is not even in your result).

          – myrmica
          Jan 2 at 14:09













          I am unsure what the counts dictionary elements are.

          – user1903663
          Jan 2 at 16:41





          I am unsure what the counts dictionary elements are.

          – user1903663
          Jan 2 at 16:41











          0














          I first convert the list of your score to a dictionary object using itertools, then iterating through each key, and for each key, compare the values available in the list
          and add accordingly the score you provided and since in this approach you will always add the value 1 because you will always compare it with itself so at end i decrease 1 from the final score there may be a better approach for this



          ls = ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
          d = dict(itertools.zip_longest(*[iter(ls)] * 2, fillvalue=""))
          values= d.values()
          for item in d.keys():
          score=0
          for i in values:
          if d[item]>i:
          score+=2
          elif d[item]==i:
          score+=1
          else:
          pass
          print(item,":",score-1)


          Output:



          2 : 7
          3 : 4
          4 : 10
          5 : 2
          7 : 0
          1 : 7
          6 : 12





          share|improve this answer



















          • 1





            also wonderful, thank you. So many cool answers to this problem which I have been struggling with for days. Thank you.

            – user1903663
            Jan 2 at 14:20






          • 1





            The zipping part is clever, took me a moment to understand. Now I see it's in the itertools recipes as grouper. A simple builtin zip would work as well in this case.

            – myrmica
            Jan 2 at 14:59











          • @myrmica Yes, actually i also don't know this before, but while searching for the solution how to convert list into dict i found that response. and learned new thing with it

            – Gaurav
            Jan 2 at 16:15
















          0














          I first convert the list of your score to a dictionary object using itertools, then iterating through each key, and for each key, compare the values available in the list
          and add accordingly the score you provided and since in this approach you will always add the value 1 because you will always compare it with itself so at end i decrease 1 from the final score there may be a better approach for this



          ls = ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
          d = dict(itertools.zip_longest(*[iter(ls)] * 2, fillvalue=""))
          values= d.values()
          for item in d.keys():
          score=0
          for i in values:
          if d[item]>i:
          score+=2
          elif d[item]==i:
          score+=1
          else:
          pass
          print(item,":",score-1)


          Output:



          2 : 7
          3 : 4
          4 : 10
          5 : 2
          7 : 0
          1 : 7
          6 : 12





          share|improve this answer



















          • 1





            also wonderful, thank you. So many cool answers to this problem which I have been struggling with for days. Thank you.

            – user1903663
            Jan 2 at 14:20






          • 1





            The zipping part is clever, took me a moment to understand. Now I see it's in the itertools recipes as grouper. A simple builtin zip would work as well in this case.

            – myrmica
            Jan 2 at 14:59











          • @myrmica Yes, actually i also don't know this before, but while searching for the solution how to convert list into dict i found that response. and learned new thing with it

            – Gaurav
            Jan 2 at 16:15














          0












          0








          0







          I first convert the list of your score to a dictionary object using itertools, then iterating through each key, and for each key, compare the values available in the list
          and add accordingly the score you provided and since in this approach you will always add the value 1 because you will always compare it with itself so at end i decrease 1 from the final score there may be a better approach for this



          ls = ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
          d = dict(itertools.zip_longest(*[iter(ls)] * 2, fillvalue=""))
          values= d.values()
          for item in d.keys():
          score=0
          for i in values:
          if d[item]>i:
          score+=2
          elif d[item]==i:
          score+=1
          else:
          pass
          print(item,":",score-1)


          Output:



          2 : 7
          3 : 4
          4 : 10
          5 : 2
          7 : 0
          1 : 7
          6 : 12





          share|improve this answer













          I first convert the list of your score to a dictionary object using itertools, then iterating through each key, and for each key, compare the values available in the list
          and add accordingly the score you provided and since in this approach you will always add the value 1 because you will always compare it with itself so at end i decrease 1 from the final score there may be a better approach for this



          ls = ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
          d = dict(itertools.zip_longest(*[iter(ls)] * 2, fillvalue=""))
          values= d.values()
          for item in d.keys():
          score=0
          for i in values:
          if d[item]>i:
          score+=2
          elif d[item]==i:
          score+=1
          else:
          pass
          print(item,":",score-1)


          Output:



          2 : 7
          3 : 4
          4 : 10
          5 : 2
          7 : 0
          1 : 7
          6 : 12






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 12:42









          GauravGaurav

          180110




          180110








          • 1





            also wonderful, thank you. So many cool answers to this problem which I have been struggling with for days. Thank you.

            – user1903663
            Jan 2 at 14:20






          • 1





            The zipping part is clever, took me a moment to understand. Now I see it's in the itertools recipes as grouper. A simple builtin zip would work as well in this case.

            – myrmica
            Jan 2 at 14:59











          • @myrmica Yes, actually i also don't know this before, but while searching for the solution how to convert list into dict i found that response. and learned new thing with it

            – Gaurav
            Jan 2 at 16:15














          • 1





            also wonderful, thank you. So many cool answers to this problem which I have been struggling with for days. Thank you.

            – user1903663
            Jan 2 at 14:20






          • 1





            The zipping part is clever, took me a moment to understand. Now I see it's in the itertools recipes as grouper. A simple builtin zip would work as well in this case.

            – myrmica
            Jan 2 at 14:59











          • @myrmica Yes, actually i also don't know this before, but while searching for the solution how to convert list into dict i found that response. and learned new thing with it

            – Gaurav
            Jan 2 at 16:15








          1




          1





          also wonderful, thank you. So many cool answers to this problem which I have been struggling with for days. Thank you.

          – user1903663
          Jan 2 at 14:20





          also wonderful, thank you. So many cool answers to this problem which I have been struggling with for days. Thank you.

          – user1903663
          Jan 2 at 14:20




          1




          1





          The zipping part is clever, took me a moment to understand. Now I see it's in the itertools recipes as grouper. A simple builtin zip would work as well in this case.

          – myrmica
          Jan 2 at 14:59





          The zipping part is clever, took me a moment to understand. Now I see it's in the itertools recipes as grouper. A simple builtin zip would work as well in this case.

          – myrmica
          Jan 2 at 14:59













          @myrmica Yes, actually i also don't know this before, but while searching for the solution how to convert list into dict i found that response. and learned new thing with it

          – Gaurav
          Jan 2 at 16:15





          @myrmica Yes, actually i also don't know this before, but while searching for the solution how to convert list into dict i found that response. and learned new thing with it

          – Gaurav
          Jan 2 at 16:15


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005909%2fhow-can-i-loop-through-a-python-list-and-perform-math-calculations-on-elements-o%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

          Npm cannot find a required file even through it is in the searched directory