Reputation: 151
I currently have some Python code that samples a sine wave over a given number of steps:
import numpy as np
step = 2*pi / 20
time = np.arange(0,2*pi + step,step)
x_range = np.sin(time)
print(x_range)
I would now like to insert two separate characters,'m' and 'np' after each existing entry in x_range
, such that the final list looks something like this:
[value1, m, np, value2, m, np, value3, m, np, value4 .....]
Does anyone know how this can be done?
Thanks in advance
Upvotes: 0
Views: 437
Reputation: 2406
It is also possible using list comprehension:
[item for sublist in [[ele, 'm', 'np'] for ele in x_range] for item in sublist]
Here you create a list with multiple lists [ele, 'm', 'np']
and you can unpack that list.
Or using list:
l = list(x_range)
for i in range(len(l), 0, -1):
l.insert(i, 'np')
l.insert(i, 'm')
Upvotes: 0
Reputation:
Make use of a comprehension to make it easy and succint.
new_list = []
{new_list.extend([e, 'm', 'np']) for e in x_range}
print(new_list)
This produces:
[value1, 'm', 'np', value2, 'm', 'np', value3, 'm', 'np', ...]
Upvotes: 1
Reputation: 1339
Something like that should do the work:
import numpy as np
step = 2*pi / 20
time = np.arange(0,2*pi + step,step)
x_range = np.sin(time)
new_list = list()
for i in x_range:
new_list.append(i)
new_list.append('m')
new_list.append('np')
print(new_list)
Just build a new list and add to it the value followed by the other two characters that you want and repeat the process for each value using for loop.
The output from the above code will be:
[0.0, 'm', 'np', 0.3090169943749474, 'm', 'np', 0.5877852522924731, 'm', 'np', 0.8090169943749475, 'm', 'np', 0.9510565162951535, 'm', 'np', 1.0, 'm', 'np', 0.9510565162951536, 'm', 'np', 0.8090169943749475, 'm', 'np', 0.5877852522924732, 'm', 'np', 0.3090169943749475, 'm', 'np', 1.2246467991473532e-16, 'm', 'np', -0.3090169943749473, 'm', 'np', -0.587785252292473, 'm', 'np', -0.8090169943749473, 'm', 'np', -0.9510565162951535, 'm', 'np', -1.0, 'm', 'np', -0.9510565162951536, 'm', 'np', -0.8090169943749476, 'm', 'np', -0.5877852522924734, 'm', 'np', -0.3090169943749477, 'm', 'np', -2.4492935982947064e-16, 'm', 'np']
Upvotes: 0