从列表列表中删除用户名

2024-04-29 10:56:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于tweets的列表,我需要删除用户名

[['@Hegelbon','That','heart','sliding','into','the','waste','basket','.',':('],['“','@ketchBurning',':','I','hate','Japanese','call','him','"','bani','"',
':(',':(','”','Me','too'], ... ]

主要的问题是我不知道如何处理列表列表。我尝试了以下代码,但没有成功:

import re

    for element in tweets:
        for word in element:
            re.sub('@[^\s]+','', tweets)

请帮忙


Tags: theinre列表forthatelementtweets
2条回答

使用列表迭代:

mylist = [['@Hegelbon','That','heart','sliding','into','the','waste','basket','.',':('],['“','@ketchBurning',':','I','hate','Japanese','call','him','"','bani','"',
':(',':(','”','Me','too'] ]



newlist = [ [item for item in sublist if not item.startswith('@')] for sublist in mylist]

可以使用嵌套列表理解来筛选以@开头的字符串(假设列表列表存储为变量l):

[[i for i in s if not i.startswith('@')] for s in l]

这将返回:

[['That', 'heart', 'sliding', 'into', 'the', 'waste', 'basket', '.', ':('], ['“', ':', 'I', 'hate', 'Japanese', 'call', 'him', '"', 'bani', '"', ':(', ':(', '”', 'Me', 'too']]

相关问题 更多 >