【问题标题】:Append string to new list if it doesn't include certain words如果它不包含某些单词,则将字符串附加到新列表
【发布时间】:2020-10-30 06:40:07
【问题描述】:
bad_words = ['Hi', 'hello', 'cool']
new_strings = []
for string in old_strings:
    if bad_words not in old_strings:
        new_strings.append(string)

如何遍历 bad_words 使其不包含包含它们的字符串?

【问题讨论】:

  • 什么意思?需要更多澄清/示例。
  • if语句if string not in bad_words:中的更改顺序
  • @frigolit_tarzan,我添加了一个可能是您问题的替代解决方案的答案。

标签: python for-loop if-statement any


【解决方案1】:

any() 与列表理解一起使用:

bad_words = ['Hi', 'hello', 'cool']
new_strings = [string 
               for string in old_strings 
               if not any(bad_word in string for bad_word in bad_words)]

【讨论】:

    【解决方案2】:
    bad_words = ['Hi', 'hello', 'cool']
    new_strings = []
    for string in old_strings:
        if string not in bad_words: 
            new_strings.append(string)
    

    你的问题不清楚,但我认为这是基于一些假设的答案

    【讨论】:

    • 我猜是反过来的。
    【解决方案3】:

    我认为您使用了错误的数据结构。如果您想在集合中使用唯一值,您应该使用 set 而不是列表。

    bad_words = {'Hi', 'hello', 'cool'} # this is a set
    
    # now if you want to add words to this set, call the update method
    new_strings = []
    bad_words.update(new_strings)
    

    您始终可以将集合转换为字符串,如下所示:

    bad_words = {'Hi', 'hello', 'cool'}
    l = list(bad_words)
    

    有关何时使用 set/list/dict 的更多信息,请查看this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多