-1

I want to sort data in this way :

teams = ['Team1','Team2','Team3','Team4']
odds = ['2','2.5','3','2.1','2.8','1.9']

json = { 
          { 
            'Team1 - Team2',
            '2, 2.5, 3'
          },
          { 
            'Team3 - Team4',
            '2.1, 2.8, 1.9'
          }
       }

How can I first create :

sort_teams = [ 'Team1 - Team2', 'Team3 - Team4' ]
schuch
  • 11
  • 2
  • 6
    your `json` variable isn't valid json. and it's not valid python either. you can't have a set inside another set. – jkr Sep 03 '21 at 20:45
  • Unclear how `odds` list maps to teams, but see https://stackoverflow.com/questions/5764782/iterate-through-pairs-of-items-in-a-python-list – OneCricketeer Sep 03 '21 at 20:48
  • See the `itertools` documentation for a function that can iterate over a list 2 (or 3, or 4, ...) items at a time. – chepner Sep 03 '21 at 20:49
  • 1
    I think you want to chunk each list into a fixed number of parts (e.g. quarters) and then you can just zip them together. – Kenny Ostrom Sep 03 '21 at 20:51
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 07 '21 at 23:17

1 Answers1

0

My guess is that you probably want to create a list of dictionaries, where the values are a list of teams and odds. You are asking to have them as strings, which you can do but I suspect isn't ultimately what you need. In any case, here's how to do both.

You can use numpy to split each list into two halves, and iterate over each half of the two lists in parallel by using zip. Then it's a matter of using .join if you really want a string, or .tolist() if you end up wanting a list.

import numpy as np

teams = ['Team1','Team2','Team3','Team4']
odds = ['2','2.5','3','2.1','2.8','1.9']

out = []
for t,o in zip(np.array_split(teams,2),np.array_split(odds,2)):
    out.append({
        'team_str': ' - '.join(t),
        'odds_str': ', '.join(o),
        'team_list': t.tolist(),
        'odds_list': o.tolist()
    })

Output

[
    {
        'team_str': 'Team1 - Team2',
        'odds_str': '2, 2.5, 3', 
        'team_list': ['Team1', 'Team2'],
        'odds_list': ['2', '2.5', '3']
    }, 
    {
        'team_str': 'Team3 - Team4',
        'odds_str': '2.1, 2.8, 1.9',
        'team_list': ['Team3', 'Team4'],
        'odds_list': ['2.1', '2.8', '1.9']
    }
]
Chris
  • 15,819
  • 3
  • 24
  • 37