试图从列表中删除数字字符,字符将不会删除,我不知道为什么

2024-09-27 17:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个程序,从命令行上的一个文件中获取输入,然后它会接受来自该文件的输入作为变量。最后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 = ""

Tags: ofthetonameselfinputdeflist
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']

试试这个:

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']

相关问题 更多 >

    热门问题