N. J
N. J

Reputation: 480

How to print long list with a short nested list using itertools.zip_longest?

I have following data:

HEADERS = ['OTHER','DIFF']
my_hosts = [['hostc', '10.0.0.4' ], ['hosta', '10.0.0.2'], ['hostb', '10.0.0.3'] ]
other_hosts = ['hosta', 'hostb', 'hostc', 'hostd' ]

The problem here is that one list is "longer" than the other in terms of number of elements. I have tried to experiment with the itertools.zip_longes, however I'm not able to print the elements in the nested list separately. Reason is: When it is suppose to print hostd it will say index out of range.

What I have tried

print(("{} \t {}").format(HEADERS[0], HEADERS[1]))

for my, other in itertools.zip_longest(sorted(my_hosts), sorted(other_hosts), fillvalue=''):
    print(("{} \t {}: {}).format(other, my[0][0], my[0][1]))

Desired output:

OTHER       DIFF
hosta       hosta: 10.0.0.2
hostb       hostb: 10.0.0.3
hostc       hostc: 10.0.0.4
hostd

Also had a quick look at: How to get the value in a nested list using itertools zip-longest

Upvotes: 1

Views: 51

Answers (1)

user1098490
user1098490

Reputation: 488

Working solution:

import itertools

HEADERS = ['OTHER','DIFF']
my_hosts = [['hostc', '10.0.0.4' ], ['hosta', '10.0.0.2'], ['hostb', '10.0.0.3'] ]
other_hosts = ['hosta', 'hostb', 'hostc', 'hostd' ]

print(("{} \t {}").format(HEADERS[0], HEADERS[1]))

for a,b in itertools.zip_longest(sorted(other_hosts),sorted(my_hosts)):
  if b is not None:
    print(("{} \t {}: {}").format(a, b[0], b[1]))
  else:
    print(a)

OUTPUT

OTHER    DIFF
hosta    hosta: 10.0.0.2
hostb    hostb: 10.0.0.3
hostc    hostc: 10.0.0.4
hostd

Upvotes: 1

Related Questions