Search code examples
pythonlist-comprehension

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


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']]

Solution

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