You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Discord.py异步环境下如何用集合对比列表找差异?

解决TypeError: unsupported operand type(s) for -: 'coroutine' and 'coroutine'

错误原因

你传入对比函数的f1、f2不是预期的字符串,而是协程对象。大概率是你获取这两个字符串时调用了异步方法(比如读取文件、调用Discord API),但没有加await就直接传参,导致函数里的File1.splitlines()实际是在协程对象上调用,最终set()里装的是协程而非字符串行,触发减法操作错误。和切换到commands.Bot无关。

修复步骤

  • 先确保获取到实际的字符串:如果f1、f2是通过异步函数获取的,必须用await等待执行完成:
    # 示例:假设从异步方法获取内容
    f1 = await some_async_function_to_get_content()
    f2 = await another_async_function_to_get_content()
    
  • 同步函数无需用await调用:你的add_compare、remove_compare是普通同步函数,直接调用即可,不要加await:
    added = add_compare(f1, f2)
    removed = remove_compare(f1, f2)
    

优化建议

可以合并两个对比函数,减少重复代码:

def compare_file_changes(old_content, new_content):
    old_lines = set(old_content.splitlines())
    new_lines = set(new_content.splitlines())
    added_lines = list(new_lines - old_lines)
    removed_lines = list(old_lines - new_lines)
    return added_lines, removed_lines

# 调用方式
added, removed = compare_file_changes(f1, f2)

内容的提问来源于stack exchange,提问作者mdssi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:19