我试图通过在此函数中找到三个错误来反转列表的顺序。该函数应该反转列表的第一个和最后一个元素,第二个元素和倒数第二个元素,依此类推。我相信我找到了两个,但我无法修复list[j] = y
的行。
def reverse(list):
"""Reverses elements of a list."""
for i in range(len(list)):
j = len(list) - i
x = list[i]
y = list[j-1]
list[i] = x
list[j] = y
l = ['a', 'b', 'c', 'd', 'e']
reverse(l)
print(l)
答案 0 :(得分:0)
我怀疑的家庭作业......
但是 - 我们都需要休息一下作业。通过循环整个列表,你可以将它反转两次。
def reverse(list):
"""Reverses elements of a list."""
for i in range(len(list)/2):
j = i + 1
x = list[i]
y = list[-j]
list[-j] = x
list[i] = y
l = ['a', 'b', 'c', 'd', 'e']
l=reverse(l)
print(l)
导致
['e', 'd', 'c', 'b', 'a']
答案 1 :(得分:-1)
使用此代码:
l = ['a', 'b', 'c', 'd', 'e']
l=l[::-1]
print(l)
为什么要复杂化这种简单的结构?或者,如果您不想这样做,请尝试使用:
l.reverse()
功能。 Python有很多功能可供使用。
答案 2 :(得分:-1)
你有几个问题。您的第一个问题是您使用的是list[j] = y
而不是list[j-1] = x
。您使用y
正确定义了j-1
,但您应该将list[j-1]
更改为另一个x
。另一个问题是你从列表的开头一直到最后。一旦你到达列表的一半以上,你就会撤消你的工作。您也不需要使用len(list)-i
,因为您可以使用-i
。这是更新的代码:
def reverse(seq):
"""Reverses elements of a list."""
for i in range(len(seq)//2):
x = seq[i]
y = seq[-i-1]
seq[i] = y
seq[-i-1] = x
l = ['a', 'b', 'c', 'd', 'e']
reverse(l)
print(l)
输出:
['e', 'd', 'c', 'b', 'a']
您甚至无需定义x
和y
。相反,这样做:
def reverse(seq):
"""Reverses elements of a list."""
for i in range(len(list)//2):
seq[i], seq[-i-1] = seq[-i-1], seq[i]
我也改变了你的命名。可能名称比seq
更好,但list
是不可接受的,因为它与内置类型冲突。