【问题标题】:Code that reads file and keeps track of "friends"读取文件并跟踪“朋友”的代码
【发布时间】:2017-11-16 23:53:32
【问题描述】:

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

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']

【问题讨论】:

  • 这个关系是对称的吗?如果 4 与 1 相关联,是否意味着 1 与 4 相关联?
  • 是的,你是对的。把数字想象成人。所以 1 将与 4 成为朋友,这意味着 4 也将与 1 成为朋友。

标签: python list file


【解决方案1】:

您可以使用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]}

【讨论】:

  • @Vcoss 如果此答案对您有帮助,请接受。谢谢!
  • 我不得不修改您的代码,以便它从文件中读取,但现在它不输出任何内容。我将编辑我的问题,以便您可以看到我做了什么。 @Ajax1234
  • @Vcoss 这很奇怪,您能否发布打印network 时返回的输出?这就是问题的根源。
  • 当然!现在用它编辑主要问题。
  • @Vcoss 感谢您的编辑!有关更改,请参阅我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
相关资源
最近更新 更多