【问题标题】:how to group by a user and show their following in python如何按用户分组并在python中显示他们的关注
【发布时间】:2018-05-22 12:30:22
【问题描述】:

以下文本是来自原始数据文本文件的示例,用于执行分析。 原始数据的格式为:user1 跟随 user2 user3 user4。例如,第一行的意思是:tony 跟随 tom 和 frank。 因此,托尼是汤姆和弗兰克的追随者。

tony tom frank  (it means tony follows tom and frank)
tom             (it means tom follows no one)
tom tony jordan (it means tom follows tony and jordan)
frank tom tony  (it means frank follows tom and tony)
jordan frank    (it means jordan follows frank)
tom frank       (it means tom follows frank)


Thus
1. tom's followers are tony and frank
2. tony's followers are tom and frank
3. frank's followers are tony and jordan and tom
4. jordan's followers is just tom.

我想计算一个表格来分析谁的关注者最多。 我想得到这样的输出:user1有关注者:user2,user3,user4 我尝试的代码没有给我正确的代码。有人可以帮忙吗?

我试过如下:

**with open("sample.txt", 'r') as fhand:
    aCompleteUserDict = {}
    aCompleteUserList = []

    for line in fhand:
        allUsers = line.split()  # This part is to convert each line in the file into a list
        for aUser in allUsers[0:]:
            aCompleteUserDict[aUser] = allUsers[1:]  
            #fan = allUsers[0]

    print(aCompleteUserDict)**




***The actual output for my try is:***
{'tony': ['tom', 'tony'], 'tom': ['frank'], 'frank': ['frank'], 'jordan': ['frank']}


***My expected output format is:***

{'tony': ['tom', 'frank'], 'tom': ['frank', 'tony']], 'frank': ['tony', 'jordan', 'tom'], 'jordan': ['tom']}

【问题讨论】:

  • 我认为您需要更清楚地解释为什么您的输入会产生此输出:'tom': ['frank', ['tony']]。为什么 Tony 在嵌套列表中?
  • @BoarGules 你好!在tony tom frankfrank tom tony 部分中,第一部分表示tony follows tom and frank。第二部分表示frank follows tom and tony。所以,汤姆有追随者:frank and tony.
  • 那为什么tom tony jordan不给'jordan': ['tom', ['tony']]呢?无论如何,嵌套是什么意思?我知道这对你来说太明显了,只需要一个例子来解释它。但对我来说不是。
  • @BoarGules 我已经更新了帖子。
  • @BoarGules 这只是一个错字!对不起

标签: python


【解决方案1】:

这是一个可以轻松适应从文件读取的解决方案。

str_1 = 'tony tom frank'
str_2 = 'tom'        
str_3 = 'tom tony jordan'
str_4 = 'frank tom tony'
str_5 = 'jordan frank'
str_6 = 'tom frank'


str_list = [str_1, str_2, str_3, str_4, str_5, str_6]


aCompleteUserDict = {}

for string in str_list:
    allUsers = string.split()
    follower, followed = allUsers[0], allUsers[1:]
    for foll in followed:
        if foll not in aCompleteUserDict.keys():
            aCompleteUserDict[foll] = [follower]
        else:
            aCompleteUserDict[foll].append(follower)

print(aCompleteUserDict)

{'tom': ['tony', 'frank'], 'frank': ['tony', 'jordan', 'tom'], 'tony': ['tom', 'frank'], 'jordan': ['tom']}

【讨论】:

  • 不客气!如果您得到的答案不是您所期望的,我建议您发表评论,以便纠正错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2019-07-12
  • 2020-08-31
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
相关资源
最近更新 更多