Home > Back-end >  How can I replace the strings of the list with the category with Python?
How can I replace the strings of the list with the category with Python?

Time:10-12

I have a list of strings like:

 df = [['cutting_board', 'knife', 'cucumber', 'plate'],
 ['bread', 'plate', 'knife', 'cutting_board'],
 ['cutting_board', 'knife', 'orange', 'plate'],
 [ 'plate', 'garlic', 'knife']]

and I have some categories like:

Kitchen_staffs =['knife', 'cutting_board', 'plate', ]
food = ['cucumber', 'bread', 'orange','garlic']

How can I replace the strings of the list with the category with Python? I want my output to look like this:

df = [['Kitchen_staffs', 'Kitchen_staffs', 'food', 'Kitchen_staffs'],
['food', 'Kitchen_staffs', 'Kitchen_staffs', 'Kitchen_staffs']]

CodePudding user response:

Here is the working code for your case

for arr in df:
    for index, name in enumerate(arr):
        if name in Kitchen_staffs:
            arr[index] = 'Kitchen_staffs'
        elif name in food:
            arr[index] = 'food'

But personally, I would recommend you to put all the "replacements" items into a dictionary, just so the code can be extended easier (i.e. not having to add more elif each time)

replacements = {
    'Kitchen_staffs': ['knife', 'cutting_board', 'plate', ],
    'food': ['cucumber', 'bread', 'orange','garlic']
}


for arr in df:
    for index, name in enumerate(arr):
        for replace_name, items in replacements.items():
            if name in items:
                arr[index] = replace_name

CodePudding user response:

Maybe like this:

new_list = [["Kichen" if word in Kitchen_staffs else "food" for word in line if word in Kitchen_staffs or word in food ] for line in df ]

CodePudding user response:

You can use list comprehension.

df = [['cutting_board', 'knife', 'cucumber', 'plate'],
      ['bread', 'plate', 'knife', 'cutting_board'],
      ['cutting_board', 'knife', 'orange', 'plate'],
      ['plate', 'garlic', 'knife']]

Kitchen_staffs =['knife', 'cutting_board', 'plate', ]
food = ['cucumber', 'bread', 'orange','garlic']

arr1 = [['Kitchen_staffs' if name in Kitchen_staffs else 'food' for idx, name in enumerate(arr)] for arr in df ]
print(arr1)

Output:

[['Kitchen_staffs', 'Kitchen_staffs', 'food', 'Kitchen_staffs'], ['food', 'Kitchen_staffs', 'Kitchen_staffs', 'Kitchen_staffs'], ['Kitchen_staffs', 'Kitchen_staffs', 'food', 'Kitchen_staffs'], ['Kitchen_staffs', 'food', 'Kitchen_staffs']]
  • Related