I have a list file made up of car details.
e.g.
1000001 Volvo v8
1000002 Mazda 2.0
I have a list file made up of car details.
e.g.
1000001 Volvo v8
1000002 Mazda 2.0
It sounds like you need to split
each line; you can use a list comprehension, as follows
cars = [line.split() for line in open("Cars.txt")]
As mentioned in the comments; you want numerical representations of the numbers. To do this you need to convert the numerical columns into numbers. E.g.
for i in range(len(cars)):
cars[i][0] = int(cars[i][0])
cars[i][-1] = int(cars[i][-1])
Then e.g. cars[0][0]
will be a number.
Alternatively, if the numbers will always be positive integers, you can condense this to:
readline = lambda l: [int(n) if n.isdigit() else n for n in l.split()]
cars = [[ readline(line) for line in open("Cars.txt")]
For any more complicated datafile reading, you might want to use e.g. pandas
.
Generators
As pointed out by zondo in the comments, you might consider using a generator
instead, which doesn't load all the data into memory (instead "generating" each element when requested); this can be done by swapping []
for ()
in the comprehension:
cars = (line.split() for line in open("Cars.txt"))
Then you can still iterate over cars as you would a list, but you can't index into a generator, as you can a list.
If you want a proper way to access all the information in the text file, you can simply define a class for it. And later fill it with information from the file. Here is an example implementation. I used unpack operator (*) here.
class Car(object):
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
def __str__(self):
return self.id + ' ' + self.name + ' ' + self.price
file = open("file.txt", 'r')
cars = [Car(*line.split()) for line in file]
for c in cars:
print c
Or use generator expression if you have a really large file
cars = (Car(*line.split()) for line in file)
In both cases it prints,
1000001 Volvo 34000
1000002 Mazda 23000
This is how you can store your results in a list
, using the split
function:
cars = []
with open("cars.txt", 'r') as f:
for line in f:
cars.append(line.split())
If you want to be able to search quickly based on your unique ID, you might be better off using a dictionary.
Here is a pure python way:
text = '1000001 Volvo 34000 1000002 Mazda 23000'
# Split text into one list
l = text.split()
# Split list into list of list every 3rd element
l = [l[i:i+3] for i in range(0, len(l), 3)]
print l
[['1000001', 'Volvo', '34000'], ['1000002', 'Mazda', '23000']]
This could be done with a regex
to produce a list
of tuple
s:
import re
text = '1000001 Volvo 34000 1000002 Mazda 23000'
l = re.findall(r'(\d+) (\w+) (\d+)', text)
print l
[('1000001', 'Volvo', '34000'), ('1000002', 'Mazda', '23000')]
If you really need a list
of list
s you can convert it:
l = [list(x) for x in l]
print l
[['1000001', 'Volvo', '34000'], ['1000002', 'Mazda', '23000']]