NumPy中重复一个字符串数组的所有元素
让我们看看如何将给定的字符串数组的所有元素重复3次。
示例 :
输入 : [‘Akash’, ‘Rohit’, ‘Ayush’, ‘Dhruv’, ‘Radhika’]
输出 : [‘AkashAkash’, ‘RohitRohit’, ‘AyushAyush’, ‘DhruvDhruv’, ‘RadvikaRadhikaRadhika’]
我们将使用numpy.char.multiply(a, i)方法完成这项任务。
numpy.char.multiply(a, i)
语法: numpy.char.multiply(a, i)
参数:
a : str或unicode的数组
i : 要重复的次数
返回:字符串的数组
例子1:重复3次。
# importing the module
import numpy as np
# created array of strings
arr = np.array(['Akash', 'Rohit', 'Ayush',
'Dhruv', 'Radhika'], dtype = np.str)
print("Original Array :")
print(arr)
# with the help of np.char.multiply()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 3)
print("\nNew array :")
print(new_array)
输出 :
Original Array :
[‘Akash’ ‘Rohit’ ‘Ayush’ ‘Dhruv’ ‘Radhika’]New array :
[‘AkashAkashAkash’ ‘RohitRohitRohit’ ‘AyushAyushAyush’ ‘DhruvDhruvDhruv’ ‘RadhikaRadhikaRadhika’]
例子2:重复2次。
# importing the module
import numpy as np
# created array of strings
arr = np.array(['Geeks', 'for', 'Geeks'])
print("Original Array :")
print(arr)
# with the help of np.char.multiply()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 2)
print("\nNew array :")
print(new_array)
输出 :
Original Array :
['Geeks' 'for' 'Geeks']
New array :
['GeeksGeeks' 'forfor' 'GeeksGeeks']