繁体   English   中英

如果元组包含标点符号,如何从列表中删除元组

[英]How to remove tuple from the list if the tuple contains punctuation mark

我有元组列表:

tupl = [('0', 'Hey'),('1', ','),('2', 'I'), ('3', 'feel'),('4', 'you'), ('5', '!')]

我想删除任何包含标点符号的元组。

我已经尝试使用以下代码,但是它适用于'!' ,只是因为我不知道如何在此代码中添加多个条件。

out_tup = [i for i in tupl if '!' not in i]
print out_tup

如何删除所有包含标点符号(例如',' )的元组?

使用any

例如:

import string

tupl = [('0', 'Hey'),('1', ','),('2', 'I'), ('3', 'feel'),('4', 'you'), ('5', '!')]
print([i for i in tupl if not any(p in i for p in string.punctuation)])

#or
print([i for i in tupl if not any(p in i for p in [",", "!"])])

if '!' not in i我们可以更改条件if '!' not in i if '!' not in iif '!' not in i and ',' not in i if '!' not in i and ',' not in i

tupl = [('0', 'Hey'),('1', ','),('2', 'I'), ('3', 'feel'),('4', 'you'), ('5', '!')]
out_tup = [i for i in tupl if '!' not in i and ',' not in i]
print(out_tup)

and ',' not in i

完整代码如下:

tupl = [('0', 'Hey'),('1', ','),('2', 'I'), ('3', 'feel'),('4', 'you'), ('5', '!')]
out_tup = [i for i in tupl if '!' not in i and ',' not in i]
print(out_tup)
import re

tupl = [('0', 'Hey'),('1', ','),('2', 'I'), ('3', 'feel'),('4', 'you'), ('5', '!')]
out_tup = [i for i in tupl if not re.search(r"[!,]", i[1])]
print(out_tup) # [('0', 'Hey'), ('2', 'I'), ('3', 'feel'), ('4', 'you')]

哪里

r"[!,]"

可以使用不需要的标点符号进行扩展

您可以使用此:

out_tup = [i for i in tupl if not i[1] in [',','!']]

使用正则表达式:

import re, string

tupl = [('0', 'Hey'), ('1', ','), ('2', 'I'), ('3', 'feel'), ('4', 'you'), ('5', '!')]
rx = re.compile('[{}]'.format(re.escape(string.punctuation)))
print(list(filter(lambda t: not rx.search(t[1]), tupl)))

输出:

[('0', 'Hey'), ('2', 'I'), ('3', 'feel'), ('4', 'you')]

Rextester上的演示。

暂无
暂无

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

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