python两个文件行的所有组合

时间:2015-12-15 21:10:47

标签: python combinations permutation

如果我有两个文件:

file car.txt

red, green, white, yellow

file color.txt

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

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

示例输出

{{1}}

3 个答案:

答案 0 :(得分:3)

你走了:

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.

答案 1 :(得分:1)

你可以简单地使用两个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)

答案 2 :(得分:0)

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创建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)))