Bababo
Bababo

Reputation: 23

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

Upvotes: 0

Views: 3595

Answers (2)

Philipp
Philipp

Reputation: 511

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

Upvotes: 2

Arcturus B
Arcturus B

Reputation: 5621

Another option is to use numpy.ndarray.

import numpy as np
list_of_numbers = [
    ('5', 2.5, 5200),
    ('6', 3.2, 5236),
    ('8', 5.4, 5287),
    ]
list_of_numbers = np.array(list_of_numbers)
p = list_of_numbers[:,1]
print(p)
# outputs: ['2.5' '3.2' '5.4']

In addition, since you're reading data from a text file, your first list should contain only str. (I really don’t understand how you get mixed strings and numbers using the method you describe in your question.) To fix that, you can either:

  • use numpy.loadtxt,
  • convert to float when switching to a ndarray: `np.array(list_of_numbers, dtype=float).

Finally, I strongly suggest that you learn about slices in Python.

Upvotes: 0

Related Questions