下面的文本是来自原始数据文本文件的样本,用于执行分析。
原始数据的格式为: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']}

最佳答案

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

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

关于python - 如何按用户分组并在python中显示其关注者,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50467758/

10-11 17:54