Reputation: 25
I am a total newbie and am doing prep work for the bootcamp. I got stuck with the the following Python exercise:
I have a nested list, say, [[1,2],[3,4]]. The first value in each sub-list is the value to repeat, the second is the amount of times to repeat that value.
I want to get a string with numbers repeated appropriate number of times, like "11, 3333". If there are multiple sets of values, they should be separated by commas; if there is only one set the comma should be omitted. I need to create a function.
I tried to create two separate sub-lists for values and number of repetitions, then np.repeat one list by another.
data_list =[[1,2],[3,4]]
num_list = [val [0] for val in data_list]
repeat_list = [val[1] for val in data_list]
result = np.repeat (num_list, repeat_list)
print (result)
[1 1 3 3 3 3]
In this case I do not know how to separate it with commas. And this is not a function.
I feel like I might need to use np.repeat with "for" loop, but I can not figure out exactly how should it look like.
Thanks.
Upvotes: 0
Views: 570
Reputation: 1815
Without for loop and numpy
', '.join(
map(lambda l: str(l[0])*l[1], data_list)
)
Each entry in list map it to string, then join those strings together
Upvotes: 0
Reputation: 4779
You could do like this.
data_list =[[1,2],[3,4]]
res = []
for i in data_list:
s = str(i[0]) * i[1]
res.append(s)
print(f'List: {res}')
print(f'String: {", ".join(res)}')
List: ['11', '3333']
String: 11, 3333
Upvotes: 0
Reputation: 1858
A possible solution :
l= [[1, 2], [3, 4]]
final=[]
for i in l:
final.append(list(str(i[0]) * i[1]))
Upvotes: 0
Reputation: 480
You could do something like this:
result = ""
for sublist in nested_list:
# For each sublist, turn the first element into a string, and multiply it by the second element, then add a comma
result += str(sublist[0]) * sublist[1] + ","
# Remove the last trailing comma
result = result[:-1]
Upvotes: 1