0

I am trying to replace a string with another string in a list, but failed and I don't know why.

For example, I have a list:

predicts = 
[['__label__1'],
 ['__label__0'],
 ['__label__1'],
 ['__label__1'],
 ['__label__0'],
 ['__label__1']]

i want to replace __label__1 with "OK" and __label__0 with "NOT OK" and save it in different variable using :

pred_label = []
for i in predicts:
  if i == '__label__1':
    pred_label.append("OK")
  else:
    pred_label.append("NOT OK")

but it failed to replace any of it

4
  • 1
    There is both a predict and predicts variable in your code, choose one or predicts is considered as empty in the second part of your code. Commented Aug 15, 2020 at 16:16
  • oke my bad, i already edited it Commented Aug 15, 2020 at 16:23
  • using list comprehension predicts = [["OK"] if item[0] is "__label__1" else ["NOT OKE"] for item in predicts] Commented Aug 15, 2020 at 16:35
  • As @kevin-mayo points out, you have a list of lists, not a list of strings. Is this a requirement of what you are trying to accomplish? Commented Aug 15, 2020 at 19:02

2 Answers 2

2

The predicts variable has two dimensions, try:

pred_label = []
for i in predicts:
    if i[0] == '__label__1':
        pred_label.append("OK")
    else:
        pred_label.append("NOT OK")
print(pred_label)
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a dictionary to map the replacement you wish to make:

substituteDict = {'__label__1': 'OK', '__label__0': 'NOT OK'}

replaced_list = []
for i in predicts:
    replaced_list.append(substituteDict.get(i[0]))

print(replaced_list)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.