I have an unequal nested list containing strings.
newlist=[['realoldbone', 'thenewhouse', 'oldking'],
['softhat', 'hatoldhat'],
['shirt', 'sweatshirt', 'myoldShirt']]
For two features say,
Features=["old","new"]
if the element in newlist
contains an element of Features
, I want to replace it with that element of Features
. So, the final answer will be like this:
newlist=[['old', 'new', 'old'],
['softhat', 'old'],
['shirt', 'sweatshirt', 'old']]
I can't think of a way how I can achieve this. I tried using for j in i for i in newlist
type of loops along with string matching but to no avail. So,
I appreciate your suggestions.
CodePudding user response:
The simplest case would be to loop through the lists and modify if feature exists:
for feature in Features:
for lst in newlist:
for i, item in enumerate(lst):
if feature in item:
lst[i] = feature
print(newlist)
Output:
[['old', 'new', 'old'], ['softhat', 'old'], ['shirt', 'sweatshirt', 'old']]