Home > Blockchain >  convert list element to 1 and 0 based on conditions in python
convert list element to 1 and 0 based on conditions in python

Time:10-23

Suppose I have a list of strings as follows:

mylist = ['x','y','z','a','b','c']

I would like to select certain element and convert them to 1, and the remaining element to 0. For example, I like to select 'z','b','c', so the resulting list would be [0, 0, 1, 0, 1, 1] I tried to use list comprehension, but I am not too familiar with how exact this should be done. I have the following, but it does not seem to work

[1 for i in mylist if i in ['z','b','c']]

CodePudding user response:

You can use list comprehension:

mylist = ['x','y','z','a','b','c']
output = [int(u in 'zbc') for u in mylist]
print(output) # [0, 0, 1, 0, 1, 1]

The expression u in 'zbc' works because each item is a character. If (more generally) the items are string, then you might want to use u in ('something', 'like', 'this') instead.

CodePudding user response:

You would need to use an if/else statement within the list comprehension.

In [7]: [1 if i in 'zbc' else 0 for i in mylist]
Out[7]: [0, 0, 1, 0, 1, 1]

CodePudding user response:

You could also count:

result = [*map('zbc'.count, mylist)]

Or for longer strings:

[*map(('foo', 'bar', 'qux').count, mylist)]
  • Related