0

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

Arcturus B
  • 5,181
  • 4
  • 31
  • 51
Bababo
  • 23
  • 1
  • 5

2 Answers2

2

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()
Philipp
  • 511
  • 4
  • 12
  • I tried this but it's not correct.. Python says that there is a mistake.. IndexError: string index out of range – Bababo Jan 02 '17 at 19:59
  • Can you edit your question and state how your file looks like and how you import the data exactly? – Philipp Jan 02 '17 at 20:01
  • This code works for me too, but i have another list.. saved in .txt file and it's written by lines... Maybe i didn't correcly import this file? – Bababo Jan 02 '17 at 20:01
  • Just to clearify: is this first codebox of your question the exact content of your file? – Philipp Jan 02 '17 at 20:07
  • I see. Importing that way will not work. I would suggest you to change the structure of your file, if you can (Just the numbers, space seperated, no empty lines at the end). You might be interested in [pickle](https://docs.python.org/3/library/pickle.html) to store and load your data. – Philipp Jan 02 '17 at 20:13
  • I would love to change the structure of my data, but i can't, because i'm learning how to programing in python for college, so i want to know solve examples like this too.. And i'm trying to solve this problem for like 1 week, but now im giving up, that's why i'm asking here.. – Bababo Jan 02 '17 at 20:15
  • I see. Readin in that data is not a trivial task. You'd have to write a parser for that specific structure. Let me see what I can do... – Philipp Jan 02 '17 at 20:21
  • Aha. Thank you so much! You helpped me a lot! :) – Bababo Jan 02 '17 at 21:30
0

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.

Community
  • 1
  • 1
Arcturus B
  • 5,181
  • 4
  • 31
  • 51