Search code examples
pythonpython-3.xlistlineelement

How i print each second element in a list full of lines? Python


I have a list of numbers like this(saved in .txt file):

list_of_numbers = [
   ('5', 2.5, 5200),
   ('6', 3.2, 5236),
   ('8', 5.4, 5287),
   ('6', 8.7, 2563)
]

And i imported this list (list is .txt file) like this:

list_of_numbers = open("list_of_numbers.txt").read().strip().split()

but now i want that python print me each second element in each line.. I tried this:

p = x[1] for x in list_of_numbers
print(p)

but it's not correct.. And i want that python printed me like this:

p = 2.5, 3.2, 5.4

Please help me..


Solution

  • You missed the brackets. Try this:

    p = [x[1] for x in list_of_numbers]
    

    To print the values, you could use

    print(', '.join([str(x) for x in p]))
    

    You also need to change the way you load the data from the file

    Full Code:

    def parse(raw):
        data = []
        for line in raw.split("\n"):
            line = line.strip()
            # --> "('5', 2.5, 5200)"
            if line.startswith("(") and line.endswith(")"):
                d = line[line.index("(")+1 : line.index(")", -1)]
                # --> "'5', 2.5, 5200"
                d = d.split(",")
                data.append([])
                for i in d:
                    i = i.strip()
                    try:
                        i = float(i)
                    except:
                        pass
                    data[-1].append(i)
        return data
    
    
    raw = open("list_of_numbers.txt").read()
    
    list_of_numbers = parse(raw)
    
    p = [x[1] for x in list_of_numbers]
    # --> [2.5, 3.2, 5.4, 8.7]
    print(', '.join([str(x) for x in p]))
    # ---> 2.5, 3.2, 5.4, 8.7
    

    I suggest using pickle. Storing and loading your data is easy as:

    import pickle
    data = ...
    # store
    file = open('data.txt', 'w')
    pickle.dump(data, file)
    file.close()
    # load
    file = open('data.txt', 'r')
    data = pickle.load(file)
    file.close()