简体   繁体   English

Python列表推导-与Dict比较

[英]Python List Comprehensions - Comparing with Dict

I write a code that has str data 我写了一个有str数据的代码

def characters(self, content):
    self.contentText = content.split()
# self.contentText is List here

I am sending self.contentText list to another module as: 我将self.contentText列表发送到另一个模块为:

self.contentText = Formatter.formatter(self.contentText)

In this method, I am writing below code: 在这种方法中,我正在编写以下代码:

remArticles = remArticles = {' a ':'', ' the ':'', ' and ':'', ' an ':'', '&  nbsp;':''}

contentText = [i for i in contentText if i not in remArticles.keys()]

But it is not replacing. 但这并不能替代。 Is it that remArticles should be list and not dict 是remArticles应该列出而不是dict

But I tried replacing it with list too. 但是我也尝试用list代替它。 It wouldn't simply replace. 它不会简单地替换。

ofcourse with list, below will be the code: 当然带有列表,下面是代码:

  contentText = [i for i in contentText if i not in remArticles]

This is continuation from Accessing Python List Type 这是从访问Python列表类型的延续

Initially I was trying: 最初我在尝试:

for i in remArticles:
  print type(contentText) 
  print "1"
  contentText = contentText.replace(i, remArticles[i])
  print type(contentText) 

But that threw errors: 但这引发了错误:

contentText = contentText.replace(i, remArticles[i])
AttributeError: 'list' object has no attribute 'replace'

Your question is not clear but if your goal is to convert a string to a list, remove unwanted words, and then turn the list back into a string, then you can do it like this: 您的问题尚不清楚,但是如果您的目标是将字符串转换为列表,删除不需要的单词,然后将列表转换回字符串,则可以执行以下操作:

def clean_string(s):
    words_to_remove = ['a', 'the', 'and', 'an', ' ']
    list_of_words = s.split()
    cleaned_list = [word for word in list_of_words if word not in words_to_remove]
    new_string = ' '.join(cleaned_list)
    return new_string

This is how you could do the same without converting to a list: 这是您无需转换为列表即可执行的操作:

def clean_string(s):
    words_to_remove = ['a', 'the', 'and', 'an', ' ']
    for word in words_to_remove:
        s = s.replace(word, '')
    return s

And if you wanted more flexibility in removing some words but replacing others, you could do the following with a dictionary: 而且,如果您希望在删除某些单词而替换其他单词时更加灵活,则可以使用字典执行以下操作:

def clean_string(s):
    words_to_replace = {'a': '', 'the': '', 'and': '&', 'an': '', ' ': ' '}
    for old, new in words_to_replace.items():
        s = s.replace(old, new)
    return s

Your problem is that your map contains spaces within the keys. 您的问题是您的地图在键中包含空格。 Following code solves your problem: 以下代码解决了您的问题:

[i for i in contentText if i not in map(lambda x: x.strip(), remArticles.keys())]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM