简体   繁体   中英

iterate over elements in two lists

i have two lists, i need to use the first elements of the first list to iterate over all elements in the second list. then i need to pickup the second element from the first list and iterate over all elements from the second list, then the third one ...

l1 = [25,45,33]

l2 = [70,25,45,25,25,45,25,60]

outp = []

counter = 0
def my_func():
    for x, x2 in enumerate(l2):
        if  x1 == l1[counter]:
            outp.append(x)
        return outp
counter = counter +1
        else:
            x1 != l1[counter]:
            outp.append([])


OUT = my_func()

"in my example i need the final resault to be in sub lists:"

"[0]: [1,3,4,6]"

"[1]: [2,4]"

"[2]: []"

Here is a way to do it using a dictionary comprehension combined with a list comprehension :

{x : [i for i, z in enumerate(l2) if z == y] for x, y in zip(range(0, len(l1)), l1)}

Output :

{0: [1, 3, 4, 6], 1: [2, 5], 2: []}

You can iterate over the first list and use a list comprehension to generate the indices.

def x_in_y(x, y):
    out = []
    for xx in x:
        out.append([i for i, yy in enumerate(y) if yy == xx])
    return out

l1 = [25,45,33]
l2 = [70,25,45,25,25,45,25,60]

x_in_y(l1, l2)
# returns:
[[1, 3, 4, 6], [2, 5], []]
l1 = [25, 45, 33]

l2 = [70, 25, 45, 25, 25, 45, 25, 60]

outp = []


def match_elems(l1, l2):
    for i, l1_elm in enumerate(l1):

        match_list = []
        for j, l2_elm in enumerate(l2):
            if l2_elm == l1_elm:
                match_list.append(j)

        outp.append(match_list)

    return outp


print(match_elems(l1, l2))

# Returns:
[[1, 3, 4, 6], [2, 5], []]

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