如何按用户分组并在python中显示其后续内容

时间:2018-05-22 12:30:22

标签: python

以下文本是原始数据文本文件中用于执行分析的示例。 原始数据的格式为: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']}

1 个答案:

答案 0 :(得分: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']}