0

Hi I try to get training set from a file and return a list of a pair of tuples like here [('yes', 40, 'good'),('more'), ...]

I tried to do it in this way

[('yes', 40, 'good'),('more',), ...] with the comma in the second tuple

what i really want is to remove the comma at the second tuple

Code

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

Output:

[('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',)]
ahmed
  • 51
  • 7

1 Answers1

1

I am not entirely sure what you are trying to achieve. The comma after the string just indicates that it is a one element tuple/ If you want a structure like [((str, int, str), str), ...] then you need to remove extra brackets:

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
Dluzak
  • 315
  • 1
  • 11
  • I want it to be look like this ('yes', 54, 'good'),('less') list of tow pair of tuples but without the comma after the element in the second tuple like i did here ('yes', 54, 'good'),('less',) – ahmed Oct 19 '18 at 16:35
  • This comma is a part of __repr__ method for tuple. It will always be present when printing single element tuple eg. `print(("foo",))` [https://stackoverflow.com/questions/40710455/why-single-element-tuple-is-interpreted-as-that-element-in-python]. – Dluzak Oct 19 '18 at 17:04
  • Thanks a lot for your answer – ahmed Oct 19 '18 at 17:27