Skip to content Skip to sidebar Skip to footer

Creating Lists With Loops In Python

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 lin

Solution 1:

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

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.

Solution 2:

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:

withopen('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
    for i, line inenumerate(data):
        globals()['line%d' % i] = line.split()

Solution 3:

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

withopen('ProjectEuler11Data.txt') as numbers:
    data = numbers.readlines()
    d = {}
    for i,line inenumerate(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.

Solution 4:

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 = 1for i in f.readlines()[0:2]:
    print i
    global count
    dic.update({'line%s'%count:i.split()})
    count+=1print dic

Output-

{'line2': ['2ku', 'fa', 'foa'], 'line1': ['1efu', 'ieo', 'ioew']}

Post a Comment for "Creating Lists With Loops In Python"