Python 3.x 在python3.6中反转字符数组
正在尝试反转字符数组:Python 3.x 在python3.6中反转字符数组,python-3.x,Python 3.x,正在尝试反转字符数组: 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_
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
之前停止。您需要范围来读取:
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))]
你做错了两件事: 范围不包括最后一个值,因此范围将在到达
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))]
为什么不直接使用
list(reversed(list of characters))
?不能使用reversed方法解决我的问题我必须将0设置为-1吗?既然它将排除0?为什么不直接使用list(reversed(list of characters))
?不能使用reversed方法解决我的问题?我必须将0设置为-1吗?因为它将排除0?另一个问题:如果我想在适当的位置反转字符串,下面是我的思考过程:1。声明最后一个索引2。删除第一个索引3。然后将第一个索引附加到数组4。重复此操作,直到第一个索引等于最后一个索引(在while循环之外声明)这是正确的方法吗?@koreannnnnn您可以通过交换,同时向前迭代一半的范围l[x],l[-(x+1)]=l[-(x+1)],l[x]
。这将交换第一个/最后一个,然后是第二个/第二个到最后一个…等等。另一个问题:如果我想在适当的位置反转字符串,我的思考过程如下:1。声明最后一个索引2。删除第一个索引3。然后将第一个索引附加到数组4。重复此操作,直到第一个索引等于最后一个索引(在while循环之外声明)这是正确的方法吗?@koreannnnnn您可以通过交换,同时向前迭代一半的范围l[x],l[-(x+1)]=l[-(x+1)],l[x]
。这将交换第一个/最后一个,然后是第二个/第二个到最后一个…等等。