Skip to main content
 首页 » 编程设计

python之创建空列表并进行一些操作

2025年05月04日7zhwl

这是我正在尝试做的事情。 我有一个包含字符串作为其中元素的列表。现在我想用它做两件事以上。

  1. 在类中创建空列表。
  2. 对列表中的每个元素进行操作,然后将其添加到我创建的空列表中。

到目前为止我的代码。

class aer(object): 
  def __init__(self): 
    self.value = [] 
  def rem_digit(self,s): 
    self.value.append(re.sub(" \d+"," ",s)) 
  def to_lower(self,s): 
    self.value.append(self.s.lower()) 

如果有人能指出我所犯的错误,那就太好了。 以及如何访问我在类里面创建的“列表”。

示例列表:

mki = ["@tenSjunkie We're sorry for the inconvenience. Please call the Guest Service Desk using this link http://t.co/8Zv8DFwbbu and your receipt.", 
 "@lindz_h We're sorry for the inconvenience. Please call the Guest Service Desk using this link http://t.co/Ak9fnazHZN and your receipt."] 

比上次有所进步或者说我在类(class)面前被打败了

def some_mani(old_list): 
    new_list = [] 
    for i in range(0,len(old_list)): 
        new_list.append(re.sub(" \d+"," ",old_list[i]).lower()) 
    return new_list 

我仍然想知道是否有人帮助我在 CLASS 中构建它。

请您参考如下方法:

我很难理解为什么你会想要这个,但听起来你想要一个包含字符串列表的类以及一些方法来进行一些简单的字符串操作并将结果添加到该列表.基于这个假设,这里有一些代码:

class MysteriousStringContainer(object): 
    def __init__(self): 
        self.values = [] 
 
    def remove_digits(self, s): 
        self.values.append(re.sub("\d+", " ", s)) 
 
    def to_lower(self, s): 
        self.values.append(s.lower()) 

现在您可以初始化一个 MysteriousStringContainer 并开始调用它的方法:

>>> m = MysteriousStringContainer() 
>>> print m.values 
[] 
>>> for s in mki: 
...     m.remove_digits(s) 
... 
>>> print m.values 
["@tenSjunkie We're sorry for the inconvenience. Please call the Guest Service Desk using this link http://t.co/ Zv DFwbbu and your receipt.", "@lindz_h We're sorry for the inconvenience. Please call the Guest Service Desk using this link http://t.co/Ak fnazHZN and your receipt."] 

如您所见,数字已被删除,生成的字符串在 m.values 中可用。不过,在您继续使用它之前,我必须强调,无论您想做什么,这几乎肯定都是一种糟糕的方式。如果没有围绕它的类,上面的代码会写得好得多:

>>> nodigits = re.sub("\d+", " ", mki[0]) 
>>> print nodigits 
"@tenSjunkie We're sorry for the inconvenience. Please call the Guest Service Desk using this link http://t.co/ Zv DFwbbu and your receipt." 

mki 列表中仍然有原始字符串,没有数字的新字符串存储为 nodigits 变量。我想不出有任何理由使用奇怪且不直观的类设置来混淆先前存在的功能,但如果这是您需要做的,我认为上面的代码可以做到。