简体   繁体   中英

I want to append in l1 to l2 when the index is 1

I am trying to get the output by using for loops

l1 = ["a", "b"]
l2 = [[0, 0], [0, 1], [1, 0], [1, 1]]
list1 = []

for i in range(len(l2)):
    for j in range(len(l2[i])):
        if l2[i][j] == 1:
            list1.append(l1[j])

I want to get output

[[], ["b"], ["a"], ["a", "b"]

This will do it:

[[l1[i] for i, y in enumerate(x) if y] for x in l2]

Or in a for loop:

result = []

for x in l2:
    part = []
    for i, y in enumerate(x):
        if y:
            part.append(l1[i])
    result.append(part)

To obtain the desired output you can use the following code:

l1 = ["a", "b"]
l2 = [[0, 0], [0, 1], [1, 0], [1, 1]]
output = [[l1[j] for j in range(0,len(l1)) if i[j] == 1] for i in l2]

Here is another way using numpy just in case, you need to compute for large lists :

import numpy as np
l3 = [list(l1[np.array(k)]) for k in l2]

Output :

[[], ['b'], ['a'], ['a', 'b']]
l1 = ["a", "b"]
l2 = [[0, 0], [0, 1], [1, 0], [1, 1]]
list1 = []

for i in l2:
    tm=[]
    if i[0]==1:
        tm.append(l1[0])
    if i[1]==1:
        tm.append(l1[1])
    list1.append(tm)


print(list1)

output

 [[], ['b'], ['a'], ['a', 'b']]

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