Reputation: 75
I'm trying to create 5 instances of each item in a list, and for each of those, concatenate a string up till the value '5'.
my_list=['A','B','C']
scores=[]
n=0
for i in my_list:
scores.append([my_list[n]]*5)
n+=1
print(scores)
Output
[['A', 'A', 'A', 'A', 'A'], ['B', 'B', 'B', 'B', 'B'], ['C', 'C', 'C', 'C', 'C']]
scores_list=[]
n=1
for list_of_lists in scores:
while n<6:
scores_list.append(scores[0][0]+'_'+str(n))
n+=1
print(scores_list)
Output
['A_1', 'A_2', 'A_3', 'A_4', 'A_5']
Expected
[['A_1', 'A_2', 'A_3', 'A_4', 'A_5'], ['B_1', 'B_2', 'B_3', 'B_4', 'B_5'], ['C_1', 'C_2', 'C_3', 'C_4', 'C_5']]
I've tried using more while loops but can't think of anything else. Any help would be appreciated.
Upvotes: 0
Views: 64
Reputation: 706
Please use my code. It's very simple.
my_list=['A','B','C']
scores=[[f"{c}_{i+1}" for i in range(5)] for c in my_list]
print(scores)
Upvotes: -2
Reputation: 77837
Let's focus on your current programming level. A simple loop nesting will do the job. The value that changes the fastest, goes on the inside loop:
scores = []
for letter in "ABC":
list_5 = []
for number in range(1, 6):
list_5.append(letter + '_' + str(number))
scores.append(list_5)
print(scores)
Output:
[['A_1', 'A_2', 'A_3', 'A_4', 'A_5'], ['B_1', 'B_2', 'B_3', 'B_4', 'B_5'], ['C_1', 'C_2', 'C_3', 'C_4', 'C_5']]
Upvotes: 3
Reputation: 6056
Using a nested list comprehension:
>>> [[f"{char}_{num+1}" for num in range(5)] for char in my_list]
[['A_1', 'A_2', 'A_3', 'A_4', 'A_5'], ['B_1', 'B_2', 'B_3', 'B_4', 'B_5'], ['C_1', 'C_2', 'C_3', 'C_4', 'C_5']]
Upvotes: 1
Reputation: 2118
The problem in the original code is that you never reset the value of n back to one after the first iteration. but you can even skip the n
variable by:
my_list=['A','B','C']
duplications = 5
scores=[]
for i in my_list:
scores.append([f'{i}_{n}' for n in range(1, duplications+1)])
print(scores)
Output:
[['A_1', 'A_2', 'A_3', 'A_4', 'A_5'], ['B_1', 'B_2', 'B_3', 'B_4', 'B_5'], ['C_1', 'C_2', 'C_3', 'C_4', 'C_5']]
Upvotes: 0