【问题标题】:Pythonic way to find 2 items from two lists existing in a another list从另一个列表中存在的两个列表中查找 2 个项目的 Pythonic 方法
【发布时间】:2014-08-29 12:20:07
【问题描述】:

我有一些 twitter 数据,我将文本分成带有快乐表情符号和悲伤表情符号的文本,如下所示:

happy_set = [":)",":-)","=)",":D",":-D","=D"]
sad_set = [":(",":-(","=("]

happy = [tweet.split() for tweet in data for face in happy_set if face in tweet]
sad = [tweet.split() for tweet in data for face in sad_set if face in tweet]

这是可行的,但是,happy_setsad_set 的表情符号可以在一条推文中找到。确保happy 列表仅包含来自happy_set 的表情符号的pythonic 方法是什么,反之亦然?

【问题讨论】:

  • 您希望在happy 中“只开心”。 sad 中的“只有悲伤”并丢弃“既快乐又悲伤”?
  • @Sylvain Leroux,就是这样
  • 可以在{happy,sad}_set 和推文上设置交集吗?
  • 对于这样的问题,您应该提供MCVE example,因为它可能有助于测试和消除问题的歧义。

标签: python list


【解决方案1】:

您可以尝试使用集合,特别是 set.isdisjoint。检查快乐推文中的标记集是否与sad_set 不相交。如果是的话,肯定属于happy

happy_set = set([":)",":-)","=)",":D",":-D","=D"])
sad_set = set([":(",":-(","=("])

# happy is your existing set of potentially happy tweets. To remove any tweets with sad tokens...
happy = [tweet for tweet in happy if sad_set.isdisjoint(set(tweet.split()))]

【讨论】:

  • 这会引发错误:AttributeError: 'list' object has no attribute 'isdisjoint'
【解决方案2】:

我会使用 lambda:

>>> is_happy = lambda tweet: any(map(lambda x: x in happy_set, tweet.split()))
>>> is_sad = lambda tweet: any(map(lambda x: x in sad_set, tweet.split()))

>>> data = ["Hi, I am sad :( but don't worry =D", "Happy day :-)", "Boooh :-("]
>>> filter(lambda tweet: is_happy(tweet) and not is_sad(tweet), data)
['Happy day :-)']
>>> filter(lambda tweet: is_sad(tweet) and not is_happy(tweet), data)
['Boooh :-(']

这将避免创建data 的中间副本。

如果data 真的很大,您可以将filter 替换为来自包itertoolsifilter,以获取迭代器而不是列表。

【讨论】:

    【解决方案3】:

    是你要找的吗?

    happy_set = set([":)",":-)","=)",":D",":-D","=D"])
    sad_set = set([":(",":-(","=("])
    
    happy_maybe_sad = [tweet.split() for tweet in data for face in happy_set if face in tweet]
    sad_maybe_happy = [tweet.split() for tweet in data for face in sad_set if face in tweet]
    
    happy = [item for item in happy_maybe_sad if not in sad_maybe_happy]
    sad = [item for item in sad_maybe_happy if not in happy_maybe_sad]
    

    对于happy...sad...,我坚持使用列表解决方案,因为项目的顺序可能是相关的。如果没有,最好使用set() 进行表演。是加法,集合已经提供了basic sets operations(联合、交集等)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-06
      • 2022-11-12
      • 1970-01-01
      • 2013-03-11
      • 2020-01-08
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      相关资源
      最近更新 更多