我需要执行一个迭代,该迭代输出一名球员参加其前队的所有实例。到目前为止,我有:
teams = ['team1', 'team2', 'team3', 'team4']
for previous_team, curr_team in zip(teams, teams[1:]):
print (curr_team, previous_team)
打印:
'team2', 'team1'
'team3', 'team2'
'team4', 'team3'
但是我需要更大的范围,在这个范围内,玩家不仅玩了最后一支球队,而且还玩过更远的球队,考虑所有间隔回到索引0,最后得出:
'team2', 'team1'
'team3', 'team2'
'team4', 'team3'
'team3', 'team1' <----
'team4', 'team2' <----
'team4', 'team1 <----
这是逻辑,应该应用于n个项目的列表。
我该怎么做?
答案 0 :(得分:0)
天真的方法是在您的团队中进行2次循环,然后在每个循环中用第一个元素减少第二个列表
所以:
for i in range(len(team)):
for j in range(len(team)-i):
print(team[i],team[j+i])
答案 1 :(得分:0)
如果您想要的是所有组合
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')
答案 2 :(得分:0)
您可以使用理解力尝试此操作,如果列表中出现两次,也可以删除相同的团队价值。
teams = ['team1', 'team2', 'team3', 'team4']
[(team1, team2) for team1 in teams for team2 in teams if team1 != team2]
结果:
[('team1', 'team2'), ('team1', 'team3'), ('team1', 'team4'), ('team2', 'team1'), ('team2', 'team3'), ('team2', 'team4'), ('team3', 'team1'), ('team3', 'team2'), ('team3', 'team4'), ('team4', 'team1'), ('team4', 'team2'), ('team4', 'team3')]
答案 3 :(得分:0)
您可以使用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'), ...]
然后您可以找到与您之前的球队的比赛:
previous_team = "team2"
current_team = "team3"
awkward = [previous_team in match and current_team in match for match in matches]
print(awkward)