Rock
Rock

Reputation: 2967

From string to binary list

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.

Upvotes: 0

Views: 101

Answers (3)

Tyler Ferraro
Tyler Ferraro

Reputation: 3772

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]

Upvotes: -1

Ankur Ankan
Ankur Ankan

Reputation: 3066

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]

Upvotes: 1

Volatility
Volatility

Reputation: 32300

>>> 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.

Upvotes: 6

Related Questions