bayman :
Given list1 below, how do I return a new list where the values of 'codes' contain the string 'Two' but does not contain the string 'One'?
# Example, given list1:
list1 = [{'id': 11, 'codes': ['OneSeven', 'TwoThree']}, {'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}, {'id': 33, 'codes': ['SixSeven', 'OneSix']}]
# Return list with element where 'id': 22 since the string 'Two' is in codes but 'One' isn't.
list2 = [{'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}]
Boseong Choi :
# Example, given list1:
list1 = [{'id': 11, 'codes': ['OneSeven', 'TwoThree']}, {'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}, {'id': 33, 'codes': ['SixSeven', 'OneSix']}]
list2 = [
d for d in list1
if any(
'Two' in word
for word in d['codes']
) and all(
'One' not in word
for word in d['codes']
)
]
print(list2)
output:
[{'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}]
If you don't like redundant traversing lists, you can variable alternatives.
- For python 3.8 or later, you can do this:
# Example, given list1:
list1 = [{'id': 11, 'codes': ['OneSeven', 'TwoThree']}, {'id': 22, 'codes': ['FiveTwoSix', 'Four', 'FourFive']}, {'id': 33, 'codes': ['SixSeven', 'OneSix']}]
list2 = [
d for d in list1
if 'Two' in (text := ' '.join(d['codes'])) and 'One' not in text
]
print(list2)
- Of course, using for-statement instead of comprehension, you can do this with 3.7 or earlier version.
list2 = []
for d in list1:
text = ' '.join(d['codes'])
if 'Two' in text and 'One' not in text:
list2.append(d)
- Or use function + comprehension:
def check_condition(data: dict) -> bool:
text = ' '.join(data['codes'])
return'Two' in text and 'One' not in text
list2 = [
d for d in list1 if check_condition(d)
]
Last one is quite readable, but someone might dislike declaring function which is used in only one place.
Choose a method fits your situation.