以下是一个示例代码,可以遍历一个单词数组并返回一个新的数字数组:
def word_to_number(word_array):
number_array = []
for word in word_array:
number = 0
for char in word:
number += ord(char) - ord('a') + 1 # 将字母转换为数字,a为1,b为2,以此类推
number_array.append(number)
return number_array
# 测试代码
words = ['hello', 'world', 'python']
numbers = word_to_number(words)
print(numbers)
输出结果为:
[52, 72, 98]
在上面的示例代码中,我们定义了一个名为word_to_number
的函数,该函数接受一个单词数组作为输入。我们创建了一个空的数字数组number_array
。然后,我们使用两层循环,外层循环遍历单词数组中的每个单词,内层循环遍历单词中的每个字符。对于每个字符,我们使用ord
函数将其转换为对应的ASCII码值,并将其与'a'
的ASCII码值相减,再加1,得到字母对应的数字值。最后,我们将数字值添加到number_array
数组中。最后,我们返回number_array
数组作为结果。
这样,我们就遍历了单词数组并返回了一个新的数字数组。