Reputation: 625
I want to create a new list with the 0-indexed value outside a for loop, then add to that same list using a for loop. My toy example is:
import random
data = ['t1', 't2', 't3']
masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']
for item in data:
masterlist.append([item])
for animal in animals:
number1 = random.randint(1, 100)
number2 = random.randint(1, 100)
masterlist.append([str(number1) + ',' + str(number2)])
masterlist
but this outputs:
[['col1', 'animal1', 'animal2', 'animal3'],
['t1'],
['52,69'],
['8,77'],
['75,66'],
['t2'],
['67,33'],
['85,60'],
['98,12'],
['t3'],
['60,34'],
['25,27'],
['100,25']]
My desired output is:
[['col1', 'animal1', 'animal2', 'animal3'],
['t1', '52,69', '8,77', '75,66'],
['t2', '67,33', '85,60', '98,12'],
['t3', '60,34', '25,27', '100,25']]
Upvotes: 2
Views: 84
Reputation: 6495
You can also use list comprehension as follows:
import random
data = ['t1', 't2', 't3']
masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']
for d in data:
rv = [d] + [str(random.randint(1, 100)) + ',' + str(random.randint(1, 100)) for a in animals]
masterlist.append(rv)
Or even more hardcore in a single list comprehension:
masterlist+= [[d] + [str(random.randint(1, 100)) + ',' + str(random.randint(1, 100)) for a in animals] for d in data]
Upvotes: 1
Reputation: 14516
What about this solution which refactors your code a bit?
import random
data = ['t1', 't2', 't3']
masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']
for item in data:
rv = []
rv.append(item)
for animal in animals:
number1 = random.randint(1, 100)
number2 = random.randint(1, 100)
rv.append(str(number1) + ',' + str(number2))
masterlist.append(rv)
Output:
>>> masterlist
[['col1', 'animal1', 'animal2', 'animal3'],
['t1', '88,43', '85,62', '84,21'],
['t2', '44,99', '32,54', '83,50'],
['t3', '82,87', '90,83', '91,84']]
Alternatively, the following would give the same result.
import random
data = ['t1', 't2', 't3']
masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']
for item in data:
masterlist.append([item] + [f"{random.randint(1, 100)},{random.randint(1, 100)}" for animal in animals])
Upvotes: 3
Reputation: 841
You can do something like this. Use a temp
list to store items of each iteration.
Moreover you were using to many square brackets while appending, this caused the too nested list.
import random
data = ['t1', 't2', 't3']
masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']
for item in data:
temp = []
temp.append(item)
for animal in animals:
number1 = random.randint(1, 100)
number2 = random.randint(1, 100)
temp.append(str(number1) + ',' + str(number2))
masterlist.append(temp)
print(masterlist)
Upvotes: 1