2 回答

TA贡献1155条经验 获得超0个赞
你可以这样做:
from itertools import combinations
def create_network(lst):
seen = {}
for e in lst:
for s, t in combinations(map(int, e.split()), 2):
seen.setdefault(s, set()).add(t)
seen.setdefault(t, set()).add(s)
return [(k, sorted(values)) for k, values in seen.items()]
data = ['5', '0 1', '1 2', '1 8', '2 3']
result = create_network(data)
print(result)
输出
[(0, [1]), (1, [0, 2, 8]), (2, [1, 3]), (3, [2]), (8, [1])]
一般的想法是创建一个字典,其中键是整数,值是它旁边出现的一组整数。该语句map(int, e.split())创建一个整数迭代,然后使用组合从迭代中挑选每一个可能的对,将每一对添加到字典中,最后返回值排序的元组。
更新 (不使用任何内置模块)
def combinations(m, lst):
if m == 0:
return [[]]
return [[x] + suffix for i, x in enumerate(lst) for suffix in combinations(m - 1, lst[i + 1:])]
def create_network(lst):
uniques = []
for s in lst:
for e in map(int, s.split()):
if e not in uniques:
uniques.append(e)
result = []
for number in uniques:
seen = []
for e in lst:
values = list(map(int, e.split()))
for s, t in combinations(2, values):
if s == number:
if t not in seen:
seen.append(t)
elif t == number:
if s not in seen:
seen.append(s)
if seen:
result.append((number, sorted(seen)))
return sorted(result)
data = ['5', '0 1', '1 2', '1 8', '2 3']
network = create_network(data)
print(network)
输出
[(0, [1]), (1, [0, 2, 8]), (2, [1, 3]), (3, [2]), (8, [1])]
上面的代码没有使用 set、dictionary 和任何外部模块。请注意,它可能会很慢。

TA贡献1946条经验 获得超3个赞
您可以使用列表理解:
d = ['5', '0 1', '1 2', '1 8', '2 3']
def find_edges(_d, c):
return [(a if b == c else b) for a, b in _d if c in [a, b]]
new_d = [[int(c) for c in i.split()] for i in d if len(i) > 1]
_final = []
for i in [h for d in new_d for h in d]:
if not any(j == i for j, _ in _final):
_final.append((i, find_edges(new_d, i)))
输出:
[(0, [1]), (1, [0, 2, 8]), (2, [1, 3]), (8, [1]), (3, [2])]
添加回答
举报