尝试反转字符数组:
def reverse(list_of_chars):
reversed_string = []
for x in range(len(list_of_chars)-1,0,-1):
reversed_string.append(list_of_chars[x])
我在做什么错了?
在原处反转字符串:
def reverse(list_of_chars):
last_index = list_of_chars[len(list_of_chars) - 1]
first_index = list_of_chars[0]
while(first_index != last_index):
first_index = list_of_chars[0]
list_of_chars.remove(first_index)
list_of_chars.append(first_index)
pass
答案 0 :(得分:0)
您做错了两件事:
范围不包含最后一个值,因此您的范围将在到达0
之前停止。您需要阅读以下内容:
range(len(list_of_chars) -1, -1, -1):
您需要返回列表。
def reverse(list_of_chars):
reversed_string = []
for x in range(len(list_of_chars) -1, -1, -1):
reversed_string.append(list_of_chars[x])
return reversed_string
print(reverse([1, 2, 3, 4, 5]))
# prints: [5, 4, 3, 2, 1]
您也可以理解地进行此操作,这可能更易于阅读:
def reverse(l):
return [l[-(index + 1)] for index in range(len(l))]
答案 1 :(得分:0)
list_of_chars = ['z','r','x','e','c']
def reverse(list_of_chars):
reversed_string = []
for x in range(len(list_of_chars)-1,-1,-1):
reversed_string.append(list_of_chars[x])
print(reversed_string)
reverse(list_of_chars)
output: ['c', 'e', 'x', 'r', 'z']