我有一个包含各种内容的列表,看起来与此类似:
exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
我目前正在这样迭代:
def myFunction(exList)
result = []
yElement = exList[0]
for ch in yElement:
if ch in SYMBOLS: #I have a list of symbols saved globally in another area
exList.remove(ch)
result = exList
我已经尝试了其他几种方法来解决这个问题,但我无处可去。我的问题是如何迭代列表元素并删除所有符号,然后继续下一个列表元素?任何帮助将不胜感激。
SYMBOLS = '{}()[].,:;+-*/&|<>=~'
我希望最终得到一个列表:
['JM', 'the quick brown fox', 'word']
答案 0 :(得分:4)
>>> SYMBOLS = '{}()[].,:;+-*/&|<>=~$1234567890'
>>> strings = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
>>> [item.translate(None, SYMBOLS).strip() for item in strings]
['JM', 'the quick brown fox', 'word']
如果您希望第一个字符串看起来像SYMBOLS
,并且您还缺少JM
字符,则必须将数字添加到$
。
来自文档:
S.translate(table [,deletechars]) - &gt;串
返回字符串S的副本,其中删除了可选参数deletechars中出现的所有字符,其余字符已通过给定的转换表进行映射,转换表必须是长度为256或无的字符串。如果table参数为None,则不应用任何转换,操作只删除deletechars中的字符。
你也可以用正则表达式来做,但如果你只需要一个简单的替换,这就更加清晰。
答案 1 :(得分:1)
exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
SYMBOLS = '{}()[].,:;+-*/&|<>=~'
results = []
for element in exList:
temp = ""
for ch in element:
if ch not in SYMBOLS:
temp += ch
results.append(temp)
print results
答案 2 :(得分:1)
您最初发布的代码的扩展名:
SYMBOLS = '${}()[].,:;+-*/&|<>=~1234567890'
def myFunction(exList):
result = map(lambda Element: Element.translate(None, SYMBOLS).strip(), exList)
return result
exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
print myFunction(exList)
输出:
['JM', 'the quick brown fox', 'word']
答案 3 :(得分:1)
如何使用string.translate方法并将标点符号列表传递给它?这可能是最简单的方法。
>>> exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
>>> import string
>>> cleanList = []
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> for i in exList:
cleanList.append(i.translate(None,string.punctuation+string.digits))
>>> cleanList
['JM', 'the quick brown fox', 'word ']
>>>
字符串翻译可用于从字符串中删除字符,它的使用方式如下:
>>> k = "{}()hello$"
>>> k.translate(None,string.punctuation)
'hello'
答案 4 :(得分:0)
SYMBOLS = '{}()[].,:;+-*/&|<>=~$1234567890'
strings = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
[item.translate({ord(SYM): None for SYM in SYMBOLS} ).strip() for item in strings]