Skip to content Skip to sidebar Skip to footer

Python All Combinations Of Two Files Lines

If I have two files: file car.txt ford, Chrysler, pontiac, cadillac file color.txt red, green, white, yellow What is the pythonic way to make all possible combination of color a

Solution 1:

Here you go:

import itertools

a = ['ford', 'Chrysler', 'pontiac', 'cadillac']
b = ['red', 'green', 'white', 'yellow']

for r in itertools.product(a, b):
    print (r[0] + " " + r[1])

print (list(itertools.product(a,b))) #If you would like the lists for later modification.

Solution 2:

You could simply use two for loop like this:

from __future__ import print_function  
# remove the above line if you're using Python 3.xwithopen('color.txt') as f:
    colors = ', '.join(f.read().splitlines()).split(', ')

withopen('car.txt') as f:
    for i in f:
        for car in i.strip().split(', '):
            for color in colors:
                print(car, color)

Solution 3:

Pythonic would mean using the tools available.

Use the csv module to read the comma separated line:

withopen('cars.txt') as cars_file:
    cars = next(csv.reader(cars_file))

withopen('colors.txt') as colors_file:
    colors = next(csv.reader(colors_file))

Use itertools.product to create the Cartesian product:

from itertools import product

In Python 3.x:

for car, color in product(cars, colors):
    print(car, color)

In Python 2.7:

for car, color in product(cars, colors):
    print car, color

In one line:

print('\n'.join('{car} {color}'
                .format(car=car, color=color)
                for car, color in product(cars, colors)))

Post a Comment for "Python All Combinations Of Two Files Lines"