3

I'm trying to create a sequence of lists with different variable names that correspond to different lines of a text file. My current code requires me to hard-code the number of lines in the file:

with open('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
    for line in data:
        if line == 1:
            line1 = line.split()
        if line == 2:
            line2 = line.split()
        if line == 3:
            line3 = line.split()
        if line == 4:
            line4 = line.split()

In this case, I would have to continue up to 20, which isn't that bad, but I imagine that there's an easier way that I'm not aware of. This is for a ProjectEuler problem, but there aren't any spoilers, and also I'm looking for advice on this specific task, rather than my strategy as a whole. Thanks!

kwes
  • 434
  • 2
  • 7
  • `if line == <=20` ?? – Learner Nov 24 '15 at 08:06
  • I don't understand... maybe my code is completely incorrect, but basically what I'm trying to do is create 20 different lists split by space that I can reference. Each line should have a new list with a variable name of line(line number) with its contents consisting of that line, split by spaces. – kwes Nov 24 '15 at 08:09
  • you can check out this question - http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop – iulian Nov 24 '15 at 08:12

4 Answers4

7
with open('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
lines = [line.split() for line in data]

I am not sure why you need different variable names for each line when you can have an array with all lines at the end. You can now simply access the individual lines by line[0], line[1] and so on.

elzell
  • 2,228
  • 1
  • 16
  • 26
  • This seems like pretty much what I was trying to do, but how do I access the individual numbers in the lines? Like if I were trying to access the fifth number in line[6]. Also, I thought Python didn't have arrays? What kind of structure is lines in that example? – kwes Nov 24 '15 at 08:25
  • 1
    Sure Python has arrays. You get the individual entries in a line by e.g. line[2][1], which would be entry number 1 in line number 2 (zero-based, so second entry in third line actually...) – elzell Nov 24 '15 at 08:28
  • 1
    @KyleWescott They are called lists Ref [docs](https://docs.python.org/3/tutorial/datastructures.html) – Bhargav Rao Nov 24 '15 at 08:28
1

Why not use a dict and update the locals of the script?

with open('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
    d = {}
    for i,line in enumerate(data):
        d["line"+str(i)] = line.split()
locals().update(d)

This way you will have lineX available within the scope of the script. For explaining: In python everything (almost) is an object, each object have a dict with the variables defining it, a class will have the self propertys in its dict, as well as functions for example. Even a module or script have its variables stored in a dictionary, you can access that dict by globals() for global variables that can be accesed by the outer scope or access by locals() for variables in the inner scope. As this are stored in a dictionary you can manage it just like it, calling any method available for any other dictionary object. So, for example:

locals()["myVariable"] = 5

Is creating a variable myVariable wich stores a 5 in the scope of the module.

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • Can you explain what you mean by update the locals? Sorry, I'm pretty new to Python and I've never used dict before. So if I used dict instead, would the values be split? Right now I have a 20 by 20 grid of numbers I need to categorize. – kwes Nov 24 '15 at 08:19
  • @KyleWescott, updated my answer with a brief explanation and a simple example, also added the split line, and fixed the locals call – Netwave Nov 24 '15 at 08:27
1

You can use globals() or locals() to define scope pointers names. Also enumerate() builtin function allows you to iterate through both index and value of collection. Knowing this you can do something like:

with open('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
    for i, line in enumerate(data):
        globals()['line%d' % i] = line.split()
Nhor
  • 3,860
  • 6
  • 28
  • 41
1

I assumed you want to read first 20 lines from the file- Try, -It is just for 3 lines extend this for 20 lines

f  = open(r"C:\New Text Document.txt",'rb')
lst =[]
for i in f.readlines()[0:2]:
    print i
    lst.append(i.split())

print lst

Output:

[['1efu', 'ieo', 'ioew'], ['2ku', 'fa', 'foa']]

If you want just flattened list-

lst.append(','.join(i.split()))

Output-

['1efu,ieo,ioew', '2ku,fa,foa']

EDIT- To refenence lines into the content use Dictionary.

f  = open(r"C:\New Text Document.txt",'rb')
dic = {}

count = 1
for i in f.readlines()[0:2]:
    print i
    global count
    dic.update({'line%s'%count:i.split()})
    count+=1
print dic

Output-

{'line2': ['2ku', 'fa', 'foa'], 'line1': ['1efu', 'ieo', 'ioew']}
Learner
  • 5,192
  • 1
  • 24
  • 36
  • How do I reference individual object in the list within a list? (I think that's what your solution is saying) – kwes Nov 24 '15 at 08:33