2

I have a list like list = ['happy', 'angry', 'sad', 'emotion'].

So I want to replace the list and make new list like

new_list=[1, 0, 0, 'happy']

following is the my code and it does not work.

if emotion=='happy':
list .replace('happy', '1').replace('angry', '0').replace('sad', '0').replace('emotion', 'happy')

what would be the correct way of doing this. Please help me !

ah bon
  • 9,293
  • 12
  • 65
  • 148
Chathuri Fernando
  • 950
  • 3
  • 11
  • 22
  • 1
    I'm not sure the dupe quite covers it, here's my answer anyway....replace is a string attribute, not for lists. I suggest use use a dictionary with a list comprehension to map your new values to the old ones: `d = {'happy':1, 'angry':0, 'sad':0, 'emotion':'happy'}; [d.get(item,item) for item in lst]; # [1, 0, 0, 'happy'];` – Chris_Rands Jun 01 '17 at 12:58
  • 2
    You say your expected output is `[1, 0, 0,'happy']`, but then you replace the words with _strings_, not with numbers (`.replace('happy', '1')`). So is the result supposed to have integers or strings? – Aran-Fey Jun 01 '17 at 13:00
  • 1
    You need to think about your logic and look to make it more generic. It looks like you are trying to replace the matching emotion with 1 and all others with 0 (unless it is the word `'emotion'` then replace with `emotion`, you can do this with a comprehension: `[1 if e == emotion else emotion if e == 'emotion' else 0 for e in lst]` -> `[1, 0, 0, 'happy']` – AChampion Jun 01 '17 at 13:00
  • 2
    I'm not sure that the dupe covers this, this maybe an XY problem. – AChampion Jun 01 '17 at 13:01
  • Duplicate is not true – tim Jun 01 '17 at 13:03

1 Answers1

2
list = ['happy','angry','sad','emotion']
new_list = [int(y) if y.isdigit() else y for y in [x.replace('happy', '1').replace('angry', '0').replace('sad', '0').replace('emotion', 'happy') for x in list]]

If you want to replace more than these 4 values, it would make sense to make a generalized replace-function which takes several replacements, e.g. two lists.

EDIT: Fixed in case you absolutely want numbers and not strings as output

tim
  • 9,896
  • 20
  • 81
  • 137