0

This is an extension to my previous question but in a reversed order: that is, with string -t-c-over----, is there a way to generate a binary list that all valid letters have 1 and hyphens have 0:

[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
 -  t  -  c  -  o  v  e  r  -  -  -  -

I feel sorry for the back and forth but it has to go like this.

3 Answers 3

6
>>> s = '-t-c-over----'
>>> lst = [0 if i == '-' else 1 for i in s]
>>> print lst
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]

The list comp checks if a letter is '-' - if it is, it puts a 0 in the list, otherwise it puts a 1 in.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I was stuck with iterators but forgot this simple way.
@Abhijit well I must admit your's was an interesting approach ;)
1

You can use this

string = "-t-c-over----"
[0 if i == "-" else 1 for i in string]

Output: [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]

2 Comments

Your answer adds nothing new and refrain from naming a variable something form built-in or the standard library
I am really sorry but when I had clicked on post answer no answers were posted till then. But because of my internet problem it took too much time to get posted.
-1

Another option is use a lambda function and a map function.

s = '-t-c-over----'
output = map(lambda x: 0 if x == '-' else 1, s)

Edit: Apparently this doesn't work in Python 3.2 so the practical solution would be something like this.

s = '-t-c-over----'
output = [0 if x == '-' else 1 for x in s]

3 Comments

Depending of the python version, this doesn't necessarily create a list.
Can you be more specific as to which versions of python this wouldn't work?
For instance in python3.2. There output is a map object and not a list.

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.