在python中,如何将列表中的独立项拆分为元组?

2024-06-02 10:05:57 发布

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

好的,我有一个文件,里面有一些车的名字,以及它们的年限,像这样排列,但每一辆都是一条新的线:

Ford Focus - 5
Ford Focus - 7
Ford Focus - 3
VW Golf - 2
VW Golf - 6
VW Golf - 1

我试图找到一种方法来对这个进行元组化,但是细节是这样分开的:

[(Ford Focus - 5), (Ford Focus - 7), (Ford Focus - 3), (VW Golf - 2), (VW Golf - 6), (VW Golf - 1)]

谢谢


Tags: 文件方法名字细节focus元组vwford
2条回答

列表理解

data = [(line.strip(),) for line in open('file', 'r')]

for循环

data = []
for line in open('file', 'r') # for every line in file
    lst.append( (line.strip(),) ) # strip the line, make it to a tuple and append to lst

我相信,你真正想要的是一个(brand, year)形式的元组列表。如果是这样,那么

def parse_car_file(file_path):
    with open(file_path) as car_file:
        return [line.rstrip().split(" - ") for line in car_file]

否则

def parse_car_file(file_path):
    with open(file_path) as car_file:
        return [(line.rstrip(),) for line in car_file]

相关问题 更多 >