我如何从文件中获取列表中的一对元组

时间:2018-10-18 16:14:24

标签: python list tuples

嗨,我尝试从文件中获取训练集,并返回一对像这样的元组的列表 [('yes',40,'good'),('more'),...]

我试图以此方式做

[('yes',40,'good'),('more',),...],第二个元组中带有逗号

我真正想要的是删除第二个元组中的逗号

代码

def gettrain():
# >>>>> YOUR CODE HERE
with open('health-train.txt','r') as health_test:


    d = list()
    lable = list()
    Data = (line.strip().split(',') for line in health_test)
    #Data = [(smoke, int(age), diet, lable) for smoke, age, diet, lable in Data]
    for smoke, age, diet, lable in Data:
        d.extend([(smoke, int(age), diet), (lable,)])


return d
# <<<<< END YOUR CODE

输出:

[('yes', 54, 'good'),
('less',),
('no', 55, 'good'),
('less',),
('no', 26, 'good'),
('less',),
('yes', 40, 'good'),
('more',),
('yes', 25, 'poor'),
('less',),
('no', 13, 'poor'),
('more',),
('no', 15, 'good'),
('less',),
('no', 50, 'poor'),
('more',),
('yes', 33, 'good'),
('more',),
('no', 35, 'good'),
('less',),
('no', 41, 'good'),
('less',),
('yes', 30, 'poor'),
('more',),
('no', 39, 'poor'),
('more',),
('no', 20, 'good'),
('less',),
('yes', 18, 'poor'),
('less',),
('yes', 55, 'good'),
('more',)]

1 个答案:

答案 0 :(得分:1)

我不确定您要达到的目标。 字符串后面的逗号仅表示它是一个元素元组/ 如果要使用类似[((str, int, str), str), ...]的结构,则需要删除多余的括号:

def gettrain():
# >>>>> YOUR CODE HERE
    with open('health-train.txt','r') as health_test:
        d = list()
        Data = (line.strip().split(',') for line in health_test)
        for smoke, age, diet, lable in Data:
            d.extend([((smoke, int(age), diet), lable)])

    return d
# <<<<< END YOUR CODE