Oborzil
Oborzil

Reputation: 71

How to merge list to get the mentioned output below?

I have the following code:

import itertools

host = ["computer1", "computer2"]

variants = [".some.domain.com", ".another.domain.com"]

for host in host:

    merged_list = "\n".join([host + variants_index for variants_index in variants])

    merged_list = merged_list.split()

    united = list(itertools.chain(merged_list))

    print(united)

But I want the following output: ['computer1.some.domain.com', 'computer1.another.domain.com', 'computer2.some.domain.com', 'computer2.another.domain.com']

What I am gettin now, it is this:

['computer1.some.domain.com', 'computer1.another.domain.com']

['computer2.some.domain.com', 'computer2.another.domain.com']

How to merge all of them together?

Upvotes: 0

Views: 91

Answers (3)

Keine_Eule
Keine_Eule

Reputation: 147

Try this, you don't even need itertools, and as pointed out in comments on another answer, it is even faster (than for loops or itertools.product)

united = [h + v for h in host for v in variants]

Upvotes: 3

Peter DeGlopper
Peter DeGlopper

Reputation: 37344

I think this would be simpler with a plain nested for loop:

united = []
for host in hosts:
    for variant in variants:
        united.append(host + variant)

You could collapse that to a list comprehension but I find nested list comprehensions generally more trouble than they're worth. Though profiling does indicate that they're faster, especially on large inputs.

Upvotes: 2

DarrylG
DarrylG

Reputation: 17166

Use itertools product

from itertools import product

result = [a+b for a, b in product(host, variants)]

#result: ['computer1.some.domain.com', 'computer1.another.domain.com', 'computer2.some.domain.com', 'computer2.another.domain.com']

Upvotes: 6

Related Questions