Python 如何基于其他列表中的项目从嵌套列表创建第三个列表
我有一些用户的列表Python 如何基于其他列表中的项目从嵌套列表创建第三个列表,python,loops,for-loop,if-statement,nested-lists,Python,Loops,For Loop,If Statement,Nested Lists,我有一些用户的列表 list_of_users=['@elonmusk', '@YouTube','@FortniteGame','@BillGates','@JeffBezos'] 还有一个由推特创建的嵌套列表,按单词分割 tweets_splitted_by_words=[['@MrBeastYT', '@BillGates', 'YOU’RE', 'THE', 'LAST', 'ONE', 'FINISH', 'THE', 'MISSION', '#TeamTrees'], ['@MrB
list_of_users=['@elonmusk', '@YouTube','@FortniteGame','@BillGates','@JeffBezos']
还有一个由推特创建的嵌套列表,按单词分割
tweets_splitted_by_words=[['@MrBeastYT', '@BillGates', 'YOU’RE', 'THE', 'LAST', 'ONE', 'FINISH', 'THE', 'MISSION', '#TeamTrees'], ['@MrBeastYT', '@realDonaldTrump', 'do', 'something', 'useful', 'with', 'your', 'life', 'and', 'donate', 'to', '#TeamTrees'], ['Please', 'please', 'donate']]
我想创建第三个新列表,由tweets的子列表按单词分割,前提是每个子列表至少包含一个用户。
我想要的输出:
output=[['@MrBeastYT', '@BillGates', 'YOU’RE', 'THE', 'LAST', 'ONE', 'FINISH', 'THE', 'MISSION', '#TeamTrees']]
我尝试了以下代码,但没有成功:
tweets_per_user_mentioned= []
giorgia=[]
for r in range(len(tweets_splitted_by_words)):
giorgia.append(r)
for _i in range(len(giorgia)):
if _i in range(len(list_of_users)):
tweets_per_user_mentioned.append(tweets_splitted_by_words[r])
else:
pass
print(tweets_per_user_mentioned)
由于您将在用户列表上执行查找,因此最好设置
数据结构。这大大降低了许多问题的时间复杂性
对于过滤,我只使用python的内置和列表理解
set_of_users = set(list_of_users)
filtered_tweets = [tweet for tweet in tweets_splitted_by_words \
if any(word in set_of_users for word in tweet)]