python中函数使用全局变量方法:加global

本文介绍了一个Python脚本示例,展示了如何在函数内部使用全局变量,并通过一个具体的例子说明了如何判断一个词频向量是否包含特定的高频词汇。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

common_words = obama_words.sort('count', ascending=False)['word'][:5]
common_words = set(common_words)
count = 0

def has_top_words(word_count_vector):
    # extract the keys of word_count_vector and convert it to a set
    unique_words = word_count_vector.keys()
    unique_words = set(unique_words)
    
    returnWord = common_words.issubset(unique_words)
    
    global count
    if returnWord == True:
        count = count + 1

    # return True if common_words is a subset of unique_words
    # return False otherwise
    return returnWord

wiki['has_top_words'] = wiki['word_count'].apply(has_top_words)
print(count)

上述代码中,函数has_top_words需要用到count这个全局变量,定义在函数之外,函数中使用前,需要在count前加global
 

代码运行后如下:

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值