python两个文件行的所有组合

2024-09-28 05:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有两个文件:

文件汽车.txt

ford, Chrysler, pontiac, cadillac 

文件颜色.txt

^{pr2}$

什么是Python式的方法,使所有可能的结合颜色和汽车?在

示例输出

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

Tags: 文件方法txt示例颜色greenred汽车
3条回答

您可以简单地使用两个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意味着使用可用的工具。在

使用^{}模块读取逗号分隔的行:

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

使用^{}创建Cartesian product

^{pr2}$

在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)))

相关问题 更多 >

    热门问题