ali baig
ali baig

Reputation: 71

Remove item from list if a string from another object contains substring

I am trying to remove items from slices(list) whose substring is a part of pic(string) value from status2. I have tried various ways but there is always some issue such as sometimes it doesn't iterate over every item, sometimes it returns the exact same list.

slices = ['face_06_01.png', 'face_B45_06_01.png', 'face_gh_06_01.png', 'face_HJ_06_01.png']
status2 = [{'key': 1, 'pic': 'face_01_01.png', 'status': 2}, {'key': 2, 'pic': 'face__B45_02_01.png', 'status': 2}, {'key': 4, 'pic': 'face_gh_04_01.png', 'status': 2}]

for part in slices:
    pic_name = part[:-10]
    for status2_pic in status2:
        if pic_name in status2_pic['pic']:
            slices.remove(part)
            break

Output I get:

slices = ['face_B45_06_01.png', 'face_HJ_06_01.png']

Output I want according to the sample data:

slices = ['face_HJ_06_01.png']

This is where I am testing the code for now: enter image description here

Upvotes: 2

Views: 136

Answers (2)

Ram
Ram

Reputation: 4779

You can try something like this using List Comprehension.

  • I am using .startswith() to specifically filter out results that start with the substring.
  • If you just want that substring to exists irrespective of position. Use in.

    if s in i['pic']:

slices = ['face_06_01.png', 'face_B45_06_01.png', 'face_gh_06_01.png', 'face_HJ_06_01.png']
status2 = [{'key': 1, 'pic': 'face_01_01.png', 'status': 2}, {'key': 2, 'pic': 'face__B45_02_01.png', 'status': 2}, {'key': 4, 'pic': 'face_gh_04_01.png', 'status': 2}]

def check(s):
    for i in status2:
        if i['pic'].startswith(s):
            return True
    return False

slices = [x for x in slices if not check(x[:-9])]

print(slices)
['face_B45_06_01.png', 'face_HJ_06_01.png']

Upvotes: 2

alparslan mimaroğlu
alparslan mimaroğlu

Reputation: 1480

This should work. You don't have to remove the items one by one. List comprehensions are your friend :)

slices = [slice for slice in slices if slice[:-10] not in str(list(map(lambda x: x['pic'], status2)))]

Upvotes: 2

Related Questions