Reputation: 173
def main():
my_list = [[float(i) for i in line.split(',')] for line in open("Alpha.txt")]
print(my_list)
for elem in my_list:
listA=[]
listA = elem
print(listA)
main()
this code prints out the correct data of which im looking for, however i need to set each print from the for loop into a object. Any help as to how i would go about doing that?
[1.2, 4.3, 7.0, 0.0]
[3.0, 5.0, 8.2, 9.0]
[4.0, 3.0, 8.0, 5.6]
[8.0, 4.0, 3.0, 7.4]
Upvotes: 0
Views: 70
Reputation: 353
Try:
myList = [map(float, line.split(',')) for line in open ("Alpha.txt")]
Now you can get each line in a different variable if you want:
a = myList[0]
b = myList[1]
and so on. But since you have a list, it's better to use it and access elements using indices. Are you sure have a correct understanding of arrays?
As the other answers point out, it is dangerous and doesn't make sense to dynamically create variables.
Upvotes: 1
Reputation: 1013
This is not a good idea, let me warn you, and you should never use this in production code (it is prone to code injection), and screws up your global namespace, but it does what you asked.
You would use exec()
for this, which is a function that dynamically executes statements.
def main():
my_list = [[float(i) for i in line.split(',')] for line in open("Alpha.txt", "r")]
print(my_list)
for elem in my_list:
exec "%s = %s" % ("abcdefghijklmnopqrstuvwxyz"[my_list.index(elem)], elem) in globals()
main()
Now, your global namespace is filled with variables a, b, c, etc. corresponding to the elements.
It is also prone to exceptions, if you have more than 26 elements, you will get an IndexError, although you could work around that.
Upvotes: 1
Reputation: 25954
What you're thinking of/trying to do is to dynamically name variables.
Don't.
Either leave your data in the list
and access it via index
my_list[0] #what you were trying to assign to 'a'
my_list[0][0] #the first element in that sub-list
Or, if you have meaningful identifiers that you want to assign to each, you can use a dict
to assign "keys" to "values".
d = {}
for sublist, meaningful_identifier in zip(my_list, my_meaningful_identifiers):
d[meaningful_identifier] = sublist
Either way, leverage python data structures to do what they were supposed to do.
Upvotes: 2