简体   繁体   中英

Iterate over list items in a specific order

I need to perform an iteration which outputs all the instances where a player played his former team. So far I have:

teams = ['team1', 'team2', 'team3', 'team4']

for previous_team, curr_team in zip(teams, teams[1:]):
    print (curr_team, previous_team)

which prints:

'team2', 'team1'
'team3', 'team2'
'team4', 'team3'

But I need a wider scope, where the player has not played only the very last team, but also teams more distant in the past, contemplating all intervals back to index 0, ending up with:

'team2', 'team1'
'team3', 'team2'
'team4', 'team3'
'team3', 'team1'   <----
'team4', 'team2'   <----
'team4', 'team1    <----

This is the logic, and should be applied to a list of n items.


How do I do this?

Naives approach is to have 2 loop over your team and then reduce the second list with the first element at each loop

So:

for i in range(len(team)):
    for j in range(len(team)-i):
       print(team[i],team[j+i])

if what you want is all combinations

from itertools import combinations
teams = ['team1', 'team2', 'team3', 'team4']

for combo in combinations(teams, 2):  # 2 for pairs, 3 for triplets, etc
    print(combo)

('team1', 'team2')

('team1', 'team3')

('team1', 'team4')

('team2', 'team3')

('team2', 'team4')

('team3', 'team4')

You can try this using comprehension, also removing the same team value if occurred twice within the list.

teams = ['team1', 'team2', 'team3', 'team4']

[(team1, team2) for team1 in teams for team2 in teams if team1 != team2]

Result:

[('team1', 'team2'), ('team1', 'team3'), ('team1', 'team4'), ('team2', 'team1'), ('team2', 'team3'), ('team2', 'team4'), ('team3', 'team1'), ('team3', 'team2'), ('team3', 'team4'), ('team4', 'team1'), ('team4', 'team2'), ('team4', 'team3')]

You can do it using product :

import itertools

teams = ["team1", "team2", "team3", "team4"]

matches = itertools.product(teams, repeat=2)

print(list(matches))

# [('team1', 'team2'), ('team1', 'team3'), ('team1', 'team4'), ('team2', 'team1'), ...]

You can then find matches against your previous team:

previous_team = "team2"

current_team = "team3"

awkward = [previous_team in match and current_team in match for match in matches]

print(awkward)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM