简体   繁体   中英

Extract element in sublist using other sublist

I have 2 nested arrays

Test = [['c','d','b','t','j','n','k','s','p','t','k'],['l','u','y','r','c','b']]

Sample = [[1,0,1,1,2,0,3,4,0,0,4],[1,0,1,2,0,3]]

I want output like whenever 0 in Sample array.I want to extract corresponding letter in Test array.Both array lengths are same

Output = [['d','n','p','t],['u','c']]

This should work:

Test = [['c','d','b','t','j','n','k','s','p','t','k'],['l','u','y','r','c','b']]
Sample = [[1,0,1,1,2,0,3,4,0,0,4],[1,0,1,2,0,3]]

final_list = []
for j in range(len(Test)):
  sub_list = []
  for i in range(len(Test[j])):
    if Sample[j][i] == 0:
      sub_list.append(Test[j][i])
  final_list.append(sub_list)

Where final_list is your expected output

import numpy as np
res = [list(np.array(a)[np.array(b) == 0]) for a,b in zip(Test, Sample)]

This seems like a job for zip() and list comprehensions :

result = [
    [t for t, s in zip(test, sample) if s == 0]
    for test, sample in zip(Test, Sample)
]

Result:

[['d', 'n', 'p', 't'], ['u', 'c']]

for loop and zip() does all the work

final_list = []

for x,y in zip(Test, Sample):
    _list=[]                   # Temp. list to append to

    for i,j in zip(x,y):
        if j == 0:
                _list.append(i)
    final_list.append(_list)   # appending to final list to create list of list
    del _list                  # del. the temp_list to avoid duplicate values
    
final_list 

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