danidee
danidee

Reputation: 9634

How to get the value in a nested list using itertools.zip_longest

i have two lists and i want to use itertool.zip_longest to compare some values in the list and do something else, this is the code I've written so far

import itertools

List1  = [['a'],['B']]
List2 = ['A','b','C']

for a in List1:
    for i in itertools.zip_longest(a,List2):
        print (i)

but this is the result I'm getting, I'm still trying to wrap my head around this behavior

('a', 'A')
(None, 'b')
(None, 'C')
('B', 'A')
(None, 'b')
(None, 'C')

I'm trying to get something like this

('a', 'A')
('B', 'b')
(None, 'C')

so i can compare the values directly

Upvotes: 2

Views: 1091

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

You can use a generator expression to flatten list1:

List1  = [['a'],['B']]
List2 = ['A','b','C']

print(list(itertools.zip_longest((b for a in List1 for b in a),List2))
[('a', 'A'), ('B', 'b'), (None, 'C')]

If you want to compare just iterate over the zip_longest object unpacking:

for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
    if a == b:
        # do whatever

To set a particular defualt value use fillvalue:

List1  = [['a'],['B']]
List2 = ['A','b','C']

print(list(itertools.zip_longest((b for a in List1 for b in a),List2,fillvalue="foo")))
[('a', 'A'), ('B', 'b'), ('foo', 'C')]

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107337

For that result you need to flatten the list a that you can do it with itertools.chain:

>>> list(itertools.izip_longest(itertools.chain(*List1),List2))
[('a', 'A'), ('B', 'b'), (None, 'C')]

Upvotes: 1

Related Questions