Reputation: 23
I have a list with item in lists and I want to give them a name for each list I do not know how is the number of items in the list:
lists = [[1.0, 2.0], [3.0, 4.0, 1.0, 2.0]...]
#result:
0 = [1.0, 2.0]
1 = [3.0, 4.0, 1.0, 2.0]
... = []
#I have this script but doesn’t work
number_of_items = len(listas)
names = range(number_of_items)
for x in names:
for i in listas:
x = [i]
#any advice?
Upvotes: 1
Views: 99
Reputation: 238249
You could put them all in a dictionary, e.g.:
lists = [[1.0, 2.0], [3.0, 4.0, 1.0, 2.0], [4,5,6]]
out_dict = {}
for i,l in enumerate(lists):
out_dict[i] = l
print(out_dict)
# which gives
{0: [1.0, 2.0], 1: [3.0, 4.0, 1.0, 2.0], 2: [4, 5, 6]}
But if you use 0,1,2 as keys/names, its like using your original list anyway.
Alternatively, you can add variables to the namespace as follows:
for i,l in enumerate(lists):
locals()['v'+str(i)] = l
print(v0, v1, v2)
#[1.0, 2.0] [3.0, 4.0, 1.0, 2.0] [4, 5, 6]
Upvotes: 1
Reputation: 2185
use a dictionary
>>> lm = {}
>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> lm["l1"] = l1
>>> lm["l2"] = l2
>>> lm["l3"] = l3
>>> lm
{'l2': [4, 5, 6], 'l3': [7, 8, 9], 'l1': [1, 2, 3]}
>>> lm["l1"]
[1, 2, 3]
Upvotes: 0
Reputation: 5291
lists = [[1.0, 2.0], [3.0, 4.0, 1.0, 2.0]]
for x,i in zip(range(len(lists)),lists):
print str(x) + " = " + str(i)
The zip()
function used here is used to iterate over the two loops that you were using previously, simultaneously. This enabled the print of expected result.
Upvotes: 0