I have list of tuple:
tupl = [('0', 'Hey'),('1', ','),('2', 'I'), ('3', 'feel'),('4', 'you'), ('5', '!')]
I want to remove any tuple containing a punctuation mark.
I already tried with the following code, but it is working for '!'
, only because I don't know how to put multiple condition in this code.
out_tup = [i for i in tupl if '!' not in i]
print out_tup
How can I remove all tuples containing punctuation marks (eg ','
)?
Using any
Ex:
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 [",", "!"])])
We can change the condition if '!' not in i
if '!' not in i
to if '!' 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)
Add and ',' not in i
Full code is below:
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')]
where
r"[!,]"
can be expanded with the punctuations you don't want
您可以使用此:
out_tup = [i for i in tupl if not i[1] in [',','!']]
Using the regular expression:
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)))
Output:
[('0', 'Hey'), ('2', 'I'), ('3', 'feel'), ('4', 'you')]
Demo on Rextester .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.