【问题标题】:Trying to remove number chars from the list, the characters will not remove and I do not know why试图从列表中删除数字字符,字符不会删除,我不知道为什么
【发布时间】:2019-10-14 05:12:40
【问题描述】:

我编写了一个程序来在命令行上从文件中获取输入,然后它将文件中的输入作为变量接受。最后 3 行的一个问题是我无法从列表中删除字符 '1' '2' 和 '3',因为即使我编写了一个函数来这样做,它仍然不起作用。

我得到的输出是 ['1 bb b\n', '2 a aab\n', '3 abbba bb\n']

我需要的输出是 ['bb b', 'a aab', 'abbba bb']

谁能帮我解决这个问题?

import sys
import re
#The input of the file needs to take the maximum size of the queue
#The input needs to choose a maximum number of states or depth
#The input needs to choose the set of dominoes

maxQueueSize = 0
maxStates = 0
outPutToken = 0;
numberOfDominoes = 0
dominoesFile = 0

def remove(list):
    pattern =r'[0-9]\n'
    list = [re.sub(pattern, '', i) for i in list]
    return list

def input_words(file_name):
    f = open(file_name, 'r')
    f = f.readlines()
    j = 0
    maxQueueSize = f[0]
    maxStates = f[1]
    outPutToken = bool(f[2])
    numberOfDominoes = f[3]
    dominoesFile = f[4: 7]
    for i in dominoesFile:
        dominesFile = remove(dominoesFile)
        #dominoesFile[j] = i.split()
        j+=1
    print(dominoesFile)

if __name__ == '__main__':
    input_words(sys.argv[1])
#    print(maxQueueSize)
else :
    print("Please enter a file!")

class Domino:
    def __init__(self, top, bottom):
        self.top = ""
        self.bottom = ""

【问题讨论】:

  • 但是你的正则表达式是错误的,模式[0-9]\n 说,“找到单个出现的数字字符后跟换行符”

标签: python


【解决方案1】:

试试这个:

list = ['1 bb b\n', '2 a aab\n', '3 abbba bb\n']
list = [i.strip('0123456789\n \t') for i in list]
print(list)

在此,我们提供了要从字符串中删除的字符。

以上输出:

['bb b', 'a aab', 'abbba bb']

【讨论】:

  • 它没有用。不过还是感谢您的宝贵时间。
  • @MATT_BOOTY,您介意详细说明吗?它抛出错误了吗?还是输出不正确?我已将我的输出添加到上面的答案中,它与您在问题中的要求相匹配
  • 好吧,你们得到的输出与我不同,我不知道为什么。
  • 请分享你得到的输出
  • 知道了,已修复。
【解决方案2】:
>>> list = ['1 bb b\n', '2 a aab\n', '3 abbba bb\n']
>>> list = [i.strip()[2:] for i in list]
>>> list
['bb b', 'a aab', 'abbba bb']

【讨论】:

  • 这是我从您的解决方案中得到的输出:[' b', 'ab', 'bba bb']。
  • 所以试试[i.strip() for i in list]
猜你喜欢
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2021-12-16
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多