【问题标题】:empty list after using list comprehension使用列表推导后的空列表
【发布时间】:2020-08-10 11:11:20
【问题描述】:

在我的列表理解中,如果"RT @tiktoksaudi2:"occurrences 存在于列表中,我会尝试删除它,但我得到一个空列表,即使它不存在于列表中

test=["The way to a man's heart is through his stomach. - Sarah Willis Parton", 'A first rate soup is better than a second rate painting. - Abraham Maslow', 'A good cook is like a sorceress who dispenses happiness. - Elsa Schiaparelli', "A man's palate can, in time, become accustomed to anything. - Napoleon Bonaparte", 'Savory seasonings stimulate the appetite. - Latin Proverb', 'Cooking is an observation-based process that you can’t do if you’re so completely focused on a recipe. - Alton Brown', 'Happiness is finding three olives in your martini when you’re hungry. - Johnny Carson', 'A good meal makes a man feel more charitable toward the world than any sermon. - Arthur Pendenys', 'Wine and cheese are ageless companions, like aspirin and aches, or June and moon, or good people and noble ventures. - M. F. K. Fisher', 'For hunger is a sauce, well blended and prepared, for any food. - Chrétien de Troyes', "Without my morning coffee I'm just like a dried up piece of roast goat. - Johann Sebastian Bach", 'You know how I feel about tacos. It’s the only food shaped like a smile. A beef smile. - Earl Hickey']
        
print(test)
sh3rtext=[text.replace("RT @tiktoksaudi2:","") for text in test if "RT @tiktoksaudi2:" in text]
print(sh3rtext)

【问题讨论】:

  • 你得到一个空列表因为它在列表中不存在 - 你只在输出中包含确实包含它的项目。这种情况真的没有意义,因为 replace 不会更改不包含它的字符串。

标签: python python-3.x list higher-order-functions


【解决方案1】:

列表推导中的if 子句过滤掉任何不符合条件的项目; IE。在您的示例中,任何不包含“RT @tiktoksaudi2:”(-> 所有这些)的项目。只需省略 if "RT @tiktoksaudi2:" in text 并对所有元素进行替换调用(如果元素不包含您的字符串,这将不起作用,只返回原始字符串)以获取整个列表。

【讨论】:

  • 谢谢,我现在明白了,但它是如何准确过滤的?我认为只有当它为真时才会使替换方法起作用
  • @sambob12 它首先过滤列表,返回一个较小(或空)的列表,然后将替换功能应用于所有剩余的元素。如果您只想在返回所有元素的同时对某些元素执行该函数,请使用类似 [(text.replace(...) if ... in text else text) for text in test];但是,如上所述,您可以简单地对所有元素运行替换
  • @sambob12 如果条件("RT @tiktoksaudi2:" in text)不是True,它甚至不会调用replace函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
相关资源
最近更新 更多