Python 如何计算已定义函数的输出?

Python 如何计算已定义函数的输出?,python,function,dictionary,output,Python,Function,Dictionary,Output,我是Python新手,试图找到一种计算已定义函数输出的简单方法。我想通过定义一个函数来计算回复给定用户名的唯一用户的数量 st='@' en=' ' task1dict={} for t in a,b,c,d,e,f,g,h,i,j,k,l,m,n: if t['text'][0]=='@': print('...'),print(t['user']),print(t['text'].split(st)[-1].split(en)[0]) user=t['user'] r

我是Python新手,试图找到一种计算已定义函数输出的简单方法。我想通过定义一个函数来计算回复给定用户名的唯一用户的数量

st='@'
en=' '
task1dict={}
for t in a,b,c,d,e,f,g,h,i,j,k,l,m,n:
if t['text'][0]=='@':
    print('...'),print(t['user']),print(t['text'].split(st)[-1].split(en)[0])
    user=t['user']
    repliedto=t['text'].split(st)[-1].split(en)[0]
    task1dict.setdefault(user, set())
    task1dict[user].add(repliedto)
task1dict['realDonaldTrump'].add('joeclarkphd')
当我输入时,返回下面的内容

print(task1dict)

{'datageek88': {'fundevil', 'joeclarknet', 'joeclarkphd'},
 'fundevil': {'datageek88'},
 'joeclarkphd': {'datageek88'},
 'realDonaldTrump': {'datageek88', 'joeclarkphd'},
 'sundevil1992': {'datageek88', 'joeclarkphd'}}
然后我想打印所有回复某个用户的Twitter用户,例如,所有回复datageek88的人都是由

def print_users_who_got_replies_from(tweeter):
    for z in task1dict:
        if tweeter in task1dict[z]:
            print(z)
这会在我输入时打印以下内容:

print_users_who_got_replies_from('datageek88')

fundevil
joeclarkphd
sundevil1992
realDonaldTrump

现在,我想通过定义一个函数来计算回复的数量,该函数将显示有多少人回复了一个用户。这个函数应该以数字(4)的形式返回答案,但我似乎无法使该部分正常工作,有什么建议或帮助吗?谢谢我尝试过使用len()函数,但似乎无法实现,尽管这可能是答案。

经验法则:当你有一个可以打印很多东西的函数时,你会想“好了,现在我如何与打印的值交互?”,这是一个信号,表明您应该将这些值附加到列表中,而不是打印它们

在这种情况下,对代码最直接的修改是

def get_users_who_got_replies_from(tweeter):
    result = []
    for z in task1dict:
        if tweeter in task1dict[z]:
            result.append(z)
    return result

seq = get_users_who_got_replies_from('datageek88')
for item in seq:
    print(item)
print("Number of users who got replies:", len(seq))
额外的高级方法:严格地说,您不需要一个完整的函数来创建和返回一个基于另一个iterable的内容的列表。您可以通过列表来完成:

seq = [z for z in task1dict if 'datageek88' in task1dict[x]]
for item in seq:
    print(item)
print("Number of users who got replies:", len(seq))

非常感谢。这对我帮助很大!