读取文件并跟踪“朋友”的代码

时间:2017-11-16 23:53:33

标签: python list file

我需要一些帮助!我有一个列表中有一堆数字的文件。它看起来像这样:

0 1

1 3

4 8

4 1

我需要一种方法来查看数字的链接次数......

例如,1链接到3和4,

而4与1和8

相关联

任何提示?

目前正在使用Ajax1234建议的代码

with open(file_name) as friends:
    network = [line.rstrip('\n') for line in friends]
    d = defaultdict(list)
    data = filter(lambda x:x, [list(re.findall('\d+', i)) for i in friends])                     
    for a,b in data:
        d[int(a)].append(int(b))

    print(dict(d))

它不会输出任何内容。

打印网络时:

['0 1', '0 2', '0 3', '1 4', '1 6', '1 7', '1 9', '2 3', '2 6', '2 8', '2 9', '3 8', '3 9', '4 6', '4 7', '4 8', '5 9', '6 8', '7 8']

1 个答案:

答案 0 :(得分:4)

您可以使用collections.defaultdict

from collections import defaultdict
import re
d = defaultdict(list)
s = """
  0 1
  1 3
  4 8
  4 1
 """
network = [list(map(int, re.findall('\d+', line.rstrip('\n')))) for line in friends][1:] #for removing the single first value.
for a, b in network:
    d[a].append(b)

print(dict(d))

new_friend_lists = {a:b+[i for i in d if a in d[i]] for a, b in d.items()}
for a, b in new_friend_lists.items():
    for i in b:
       if i not in d:
            d[i].extend([c for c, e in new_friend_lists.items() if i in e])
       d[a].append(i)

final_list = {a:list(set(b)) for a, b in d.items()}

在上面发布的文件数据输出上运行上面的代码时,这是输出:

{0: [1, 2, 3], 1: [0, 9, 4, 6, 7], 2: [0, 8, 3, 6, 9], 3: [0, 8, 2, 9], 4: [8, 1, 6, 7], 5: [9], 6: [8, 1, 2, 4], 7: [8, 1, 4], 8: [2, 3, 4, 6, 7], 9: [1, 2, 3, 5]}