Skip to main content
 首页 » 编程设计

在包含 unicode 字符串的列表上调用 remove() 时,Python 给出 UnicodeWarning

2025年05月04日18soundcode

我有两个包含 unicode 字符串的列表。我正在尝试从 availablesongs 中删除也出现在 recentsongs 中的每个元素。

以下代码导致了问题(为调试而注释掉了异常子句):

for x in recentsongs: 
    #try: 
        availablesongs.remove(x) 
    #except ValueError: 
    #   pass 

当列表包含纯 ASCII 字符串时,此代码工作正常,但当引入其他语言的字符时,它会失败:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal 
  availablesongs.remove(x) 
ValueError: list.remove(x): x not in list 

错误来自 remove() 函数本身,这让我很困惑。我该如何解决这个问题?

请您参考如下方法:

我会做什么:

list(set(availablesongs)-set(recentsongs))