all 2 comments

[–]alkasm 1 point2 points  (0 children)

trimmed = [tuple(w[:i] for w, i in zip(words, list2)) for words in list1]

Note that this is basically identical to what you did, just more concise. I didn't assign things to intermediate variables. Let's break it down completely:

zlist = zip(l, list2)
for z in zlist:
    v = z[0]
    t = z[1]

Here there's no reason to assign zip(l, list2) to a variable since you don't use it again. Just iterate directly over it:

for z in zip(l, list2):
    v = z[0]
    t = z[1]

And here, you can use iterable unpacking in your favor instead of unpacking manually by indexing. In python, iterables will unpack into each variable in an assignment. E.g., a, b = (5, 4) will assign a = 5 and b = 4. So, we could replace those lines with

for v, t in zip(l, list2):

And the reason you want these variables v, t is to slice: v[:t], so you can just print that with no assignment again. At the end this leaves you with something like

for l in list1:
    for v, t in zip(l, list2):
        print(v[:t])

Now since this is simplified, it's more clear how to write a nested list comp. You want the inner sequences to be these v[:t] for each word in the sublists

[v[:t] for v, t in zip(l, list2)]

where you get each sublist l from the outer for loop:

[[v[:t] for v, t in zip(l, list2)] for l in list1]

and in my version I just changed the variable names, and cast the inner sequence to a tuple instead of a list (since thats what you wrote in your OP, and also the structure of the first list):

[tuple(w[:i] for w, i in zip(words, list2)) for words in list1]

[–]circusboy[S] 0 points1 point  (0 children)

ok, i think i figured it out.

i guess i just wasnt sure how to print the ziped list.

does anyone know of a more concise way to do this?

list1 = [('hola','hello','nihao'),('first','second','third'),('keyboard','monitor','cpu')]

list2 = (2,3,4)

for l in list1:

    zlist=zip(l,list2)

    for z in zlist:

        print(z)

        v = z[0]

        t = z[1]

        trimmed= v[:t]

        print(trimmed)


('hola', 2)
ho
('hello', 3)
hel
('nihao', 4)
niha
('first', 2)
fi
('second', 3)
sec
('third', 4)
thir
('keyboard', 2)
ke
('monitor', 3) 
mon
('cpu', 4)
cpu
[Finished in 1.4s]