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

时间:2016-03-02 17:31:43

标签: 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']
    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()函数,但似乎无法使用它,尽管它可能就是答案。

1 个答案:

答案 0 :(得分:1)

经验法则:当你有一个可以打印很多东西的功能时,你会想“现在我该如何与那些被打印的值进行交互?”,这是一个信号,你应该append那些值列表而不是打印它们。

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

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))

Bonus高级方法:严格来说,只需要根据另一个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))