-2

Suppose I have an ordered list for reference (in the example of length 10):

ref = ["tom", "was", "playing", "ball", "in", "the", "garden", "with", "his", "friends"]

And I have a list of 3 items:

words = ["ball", "garden", "friends"]

I want to convert the above ref list to a list of ones and zeros like so.. If t is in the sequence of strings, we should put a 1 at the i-th position of the output vector, otherwise it should be 0:

Output:

[0, 0, 0, 1, 0, 0, 1, 0, 0, 1]

Can I do this using a one liner?

pissall
  • 7,109
  • 2
  • 25
  • 45
  • @mkrieger1 I understand I need to rephrase my question with better language, but that's not exactly what I'm looking for. I couldn't find answers to my question and hence asked it on SO. I have got my answer – pissall Jul 22 '20 at 12:10
  • Which part exactly did you have difficulty with? This question is too broad. – mkrieger1 Jul 22 '20 at 12:11
  • @mkrieger1 I have described the problem I was facing in the description. You could help me rephrase the question title – pissall Jul 22 '20 at 12:12
  • Also, see [How to return list of booleans to see if elements of one list in another list](https://stackoverflow.com/q/14430454/7851470) – Georgy Jul 22 '20 at 14:36

1 Answers1

2

You can use list comprehension and check with in as following:

ref = ["tom", "was", "playing", "ball", "in", "the", "garden", "with", "his", "friends"]

words = ["ball", "garden", "friends"]

output = [1 if r in words else 0 for r in ref]

print(output)

Here's the working repl.it project: https://repl.it/@HarunYlmaz/PepperyShamefulCodewarrior

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35