Home > Net >  How do I make a function in python which takes a list of integers as an input and outputs smaller li
How do I make a function in python which takes a list of integers as an input and outputs smaller li

Time:11-23

I have a list of scraped betting odds as well as team names shown here. Before I can do calculations on the data to determine if I want to make a bet I want to group my data such that odds that are paired together are in their own separate list I can specifically target (groups of 2). As shown in the image, if an odd was provided of 2.15 for Wilsa Krakow this odd would be ideally paired with the 1.64 odd for Hippomanics (eSports teams hence the weird names)the team they are versing.

Essentially I just want to be able to take values from list[0] and list[1] positions and make a new list with just those values and then continue doing that (list[2] & list[3] made into a separate list, and list[4] and list[5] etc.) Just not sure how to write a function which will iterate through the list taking two values, grouping them in a new list and then repeating this process til it terminates at the end of the list. Thanks for any help in advance.

CodePudding user response:

If you only want groups of two (as opposed to groups of n), then you can hardcode n=2 and use a list comprehension to return a list of lists. This will also create a group of one at the end of the list if the length of the list is odd:

some_list = ['a','b','c','d','e']
[some_list[i:i 2] for i in range(0, len(some_list), 2)] 

This will return:

[['a', 'b'], ['c', 'd'], ['e']]
  • Related