【问题标题】:How to count the output of a defined function?如何计算定义函数的输出?
【发布时间】:2016-03-02 17:31:43
【问题描述】:

我是 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() 函数,但似乎无法让它工作,尽管它可能是答案。

【问题讨论】:

    标签: python function dictionary output


    【解决方案1】:

    经验法则:当您有一个打印很多东西的函数,并且您认为“现在我如何与打印的那些值进行交互?”时,这表明您应该 appending 这些值列表而不是打印出来。

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

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

    额外的高级方法:严格来说,您不需要一个完整的函数来根据另一个可迭代的内容创建和返回一个列表。您可以通过列表理解来做到这一点:

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

    【讨论】:

    • 谢谢!这对我帮助很大!
    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    相关资源
    最近更新 更多