python 两个文件行的所有组合

python all combinations of two files lines

如果我有两个文件:

文件car.txt

ford, Chrysler, pontiac, cadillac 

文件color.txt

red, green, white, yellow

使颜色和汽车的所有可能组合的 pythonic 方法是什么?

示例输出

ford red
ford green
ford white
ford yellow
Chrysler red
Chrysler green
and so on...

您可以像这样简单地使用两个 for 循环:

from __future__ import print_function  
# remove the above line if you're using Python 3.x

with open('color.txt') as f:
    colors = ', '.join(f.read().splitlines()).split(', ')

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

给你:

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.

Pythonic 意味着使用可用的工具。

使用csv模块读取逗号分隔行:

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

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

使用itertools.product to create the Cartesian product:

from itertools import product

在Python 3.x:

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

在 Python 2.7:

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

一行:

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