简体   繁体   中英

Python append 1 to list if condition exist and 0 to all other lists

I have 3 lists:

a_exist = []
b_exist = []
c_exist = []

i am looping through a main list of strings:

l = ['a', 'b']

for item in l:

    if 'a' in item:

        a_exist.append(1)
        b_exist.append(0)
        c_exist.append(0)

    else:

        a_exist.append(0)
        b_exist.append(0)
        c_exist.append(0)

    if 'b' in item:

        b_exist.append(1)
        a_exist.append(0)
        c_exist.append(0)

    else:

        b_exist.append(0)
        a_exist.append(0)
        c_exist.append(0)

What i am trying to get:

a_exist = [1,0]
b_exist = [0,1]
c_exist = [0,0]

Is there a better way of doing this?

l = ['a', 'b']
a_exist = [1 if 'a' in i else 0 for i in l]
c_exist = [1 if 'b' in i else 0 for i in l]
b_exist = [1 if 'c' in i else 0 for i in l]
print(a_exist, b_exist, c_exist, sep='\n')

out:

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

Just combine the list comprehension and conditional assignment . First loop through l and get each value, than check if the value match the condition, if the value match, return 1, else return 0

As an alternate take on this, your problem sounds like it would likely be better suited for a dictionary of lists. This makes it easy to extend (eg, if you want to detect other characters, you just add them to the initial list checks below) without having to add a new _exist list each time.

In [7]: checks = ['a', 'b', 'c', 'd', 'e']

In [8]: l = ['a', 'b', 'ae', 'bcd']

In [9]: ret = {k: [int(k in v) for v in l] for k in checks}

In [10]: ret
Out[10]:
{'a': [1, 0, 1, 0],
 'b': [0, 1, 0, 1],
 'c': [0, 0, 0, 1],
 'd': [0, 0, 0, 1],
 'e': [0, 0, 1, 0]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM