Removing items from list if they contain a substring
Question:
Let’s say I have a list that looks like this:
'CALSIM', '1556', '1897', '1358', '1321', '1254', '1403', '1124', '2561', '958', '712', '704', '562', '2092', '2020', '2001', '1890', '1748', 'Sky1', '1307', 'Sky29', '1802', '3429', '3522', 'Sky21'
I want to remove all instances of CALSIM
and all instances of Sky#
from my list. Is there a convenient method in Python?
Answers:
You can add more conditions if you need.
strings = ['CALSIM', '1556', '1897', '1358', '1321', '1254', '1403', '1124', '2561', '958', '712', '704', '562', '2092', '2020', '2001', '1890', '1748', 'Sky1', '1307', 'Sky29', '1802', '3429', '3522', 'Sky21']
strings = [row for row in strings if row != "CALSIM" and not row.startswith("Sky")]
List comprehension:
[x for x in YOURLIST if x is not "CALSIM" and not x.startswith("Sky")]
Let’s say I have a list that looks like this:
'CALSIM', '1556', '1897', '1358', '1321', '1254', '1403', '1124', '2561', '958', '712', '704', '562', '2092', '2020', '2001', '1890', '1748', 'Sky1', '1307', 'Sky29', '1802', '3429', '3522', 'Sky21'
I want to remove all instances of CALSIM
and all instances of Sky#
from my list. Is there a convenient method in Python?
You can add more conditions if you need.
strings = ['CALSIM', '1556', '1897', '1358', '1321', '1254', '1403', '1124', '2561', '958', '712', '704', '562', '2092', '2020', '2001', '1890', '1748', 'Sky1', '1307', 'Sky29', '1802', '3429', '3522', 'Sky21']
strings = [row for row in strings if row != "CALSIM" and not row.startswith("Sky")]
List comprehension:
[x for x in YOURLIST if x is not "CALSIM" and not x.startswith("Sky")]