python两个文件行的所有组合 [英] python all combinations of two files lines

查看:55
本文介绍了python两个文件行的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个文件:

ford, Chrysler, pontiac, cadillac 

文件color.txt

red, green, white, yellow

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

What is the pythonic way to make all possible combination of color and car?

示例输出

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

推荐答案

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

You could simply use two for loop like this:

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)

这篇关于python两个文件行的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆