重复 NumPy字符串数组的所有元素
让我们看看如何将给定字符串数组的所有元素重复 3 次。
例子 :
Input : [‘Akash’, ‘Rohit’, ‘Ayush’, ‘Dhruv’, ‘Radhika’]
Output : [‘AkashAkashAkash’, ‘RohitRohitRohit’, ‘AyushAyushAyush’, ‘DhruvDhruvDhruv’, ‘RadhikaRadhikaRadhika’]
我们将为此任务使用numpy.char.multiply(a, i)方法。
numpy.char.multiply(a, i)
Syntax : numpy.char.multiply(a, i)
Parameters :
- a : array of str or unicode
- i : number of times to be repeated
Returns : Array of strings
示例 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']
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。