To amend the single list with two Python list.

Asked 2 years ago, Updated 2 years ago, 32 views

I have two lists, but I want to remove the value in one list and replace it with this string "____".

The code I tried is as follows.

list_s = ["a","b","c","d","e"]
list_t = ["a","b"]
list_s2 = []

cnt =0
for value in list_s:
     if value == list_t[cnt]:
        del list_s[cnt]
        list_s[cnt].append("___")
     cnt += 1


print(list_s)

python list

2022-09-21 10:12

1 Answers

It is not a good idea to delete a specific index of when you are touring a list (even by index). For example, after del list_s[0] runs, list_s[0] will be just 'b' from the next line, not 'a' or anything else.

Assuming that what you're trying to implement is a kind of blanking quiz, I'll approach it with the map, lambda and thing in list

list_s = ['self-made', 'last', 'caught', 'most', 'harshly', 'punishment', 'will']
list_t = ["Harshly", "Punishment"]

list_s2 = list(map(lambda x: '___' if x in list_t else x, list_s))


2022-09-21 10:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.