【问题标题】:How to create a 3rd list from a nested list based on items in another list如何根据另一个列表中的项目从嵌套列表创建第三个列表
【发布时间】:2019-11-09 21:06:34
【问题描述】:

我有一些用户的列表

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']]

只有当每个子列表至少包含 list_of_users 中的一个用户时,我才想创建由 tweets_splitted_by_words 的子列表组成的第三个新列表。 我想要的输出:

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 loops for-loop if-statement nested-lists


    【解决方案1】:

    由于您将在用户列表中执行查找,因此最好使用set 数据结构。 Sets provide O(1) lookup 大大降低了很多问题的时间复杂度。

    对于过滤,我只使用 python 的内置 any 和列表理解

    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)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 2018-10-24
      • 1970-01-01
      相关资源
      最近更新 更多