如何列出 Python 中的所有邻居?

how to make list of all neighbors in Python?

我有如下列表。 它由 'HOME' 和 'AWAY'.

两列组成
Home     AWAY
Rangers  Twins
Yankees  RedSox
RedSox   Yankees
Cups     Yankees

我想把每支球队的所有邻居,无论主场还是客场,如下所示。

TEAM     NEIGHBOR
Rangers  [Twins]
Yankees  [RedSox, Cups]
RedSox   [Yankees]
Cups     [Yankees]

虽然我考虑过使用网络模块,但我无法解决那个问题。 提前致谢。

您可以在不使用任何第 3 方库的情况下执行类似的操作。

import sys
import json

def Whosebug():
    matches = [
        {"Home": ["Rangers", "Yankees", "RedSox", "Cups"]},
        {"Away": ["Twins", "RedSox", "Yankees", "Yankees"]}
    ]

    matchups = []
    for ih, homeTeam in enumerate(matches[0]["Home"]):
        for ia, awayTeam in enumerate(matches[1]["Away"]):
            if ih == ia:
                matchups.append({homeTeam:awayTeam})

    schedule = {}
    for idx, match in enumerate(matchups):
        homeTeam, awayTeam = list(match.items())[0]
        # add all teams to the schedule.
        schedule[homeTeam] = []
        schedule[awayTeam] = []
    
    for team in schedule:
        for match in matchups:
            homeTeam, awayTeam = list(match.items())[0]
            if awayTeam not in schedule[homeTeam]:
                schedule[homeTeam].append(awayTeam)
            if homeTeam not in schedule[awayTeam]:
                schedule[awayTeam].append(homeTeam)

    print(json.dumps(schedule,sort_keys=True, indent=4))
    
Whosebug()

What's happening?

  • First we setup our matches

  • Then we create a dictionary of the matchups {HomeTeam : AwayTeam}

  • Then we check what teams are facing each-other and adding them to that teams entry of upcoming matches.

输出:

{
  "Cups": [
    "Yankees"
  ],
  "Rangers": [
    "Twins"
  ],
  "RedSox": [
    "Yankees"
  ],
  "Twins": [
    "Rangers"
  ],
  "Yankees": [
    "RedSox",
    "Cups"
  ]
}

没有json-print

{
 'Rangers': ['Twins'], 
 'Twins':   ['Rangers'], 
 'Yankees': ['RedSox', 'Cups'], 
 'RedSox':  ['Yankees'], 
 'Cups':    ['Yankees']
}

使用networkx的解决方案:

G = nx.from_pandas_edgelist(df, source='Home', target='AWAY')
for node in G.nodes():
    print(node, list(G.neighbors(node)))

#output:
Rangers ['Twins']
Twins ['Rangers']
Yankees ['RedSox', 'Cups']
RedSox ['Yankees']
Cups ['Yankees']