为什么这两个程序返回不同的输出?

时间:2019-03-31 16:08:54

标签: python python-3.x

我有两个程序应该反转字符列表(长度为1的字符串)。第二个程序给出正确的输出,而第一个程序没有给出。

这是程序1:

string = ['h', 'e', 'l', 'l', 'l', 'o']
y = len(string) / 2
for letter in string:
    x = string.index(letter)
    if x < y:
       string[x], string[-1-x] = string[-1-x], string[x]

这是程序2:

string = ['h', 'e', 'l', 'l', 'l', 'o']
y = len(string) / 2
x = 0
while x < y:
    if x < y:
        string[x], string[-1-x] = string[-1-x], string[x]
    x += 1

我的第二个程序成功反转了字符串,但是第一个返回['o', 'e', 'l', 'l', 'l', 'h']。我很高兴找到解决方案,但宁愿使用.index()而不是计算每个循环。

2 个答案:

答案 0 :(得分:2)

第一个程序中有一个反模式。

x = string.index(letter)

请考虑当您为第二个或第三个'l' ...建立索引时x总是 为2。条件x < y会出现,并且反转'e'和第二个'l'的位置。

以下是一些调试步骤:
(请注意x在 应该分别为2、3和4的第二,第三和第四次迭代中为2。)

Iter 0:
letter = 'h'; x = 0; swap √; string = ['o', 'e', 'l', 'l', 'l', 'h']
#                                       ^------------------------^

Iter 1:
letter = 'e'; x = 1; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
#                                            ^--------------^    

Iter 2:
letter = 'l'; x = 2; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
#                                                 ^----^    

Iter 3:           !
letter = 'l'; x = 2; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
#                                                 ^----^    

Iter 4:           !
letter = 'l'; x = 2; swap √; string = ['o', 'e', 'l', 'l', 'l', 'h']
#                                            ^--------------^    

Iter 5:
letter = 'l'; x = 5; swap X; string = ['o', 'e', 'l', 'l', 'l', 'h']

Python上,您应该使用enumerate来跟踪索引:

y = len(string) / 2
for i, _ in enumerate(string):
    if i < y:
       string[i], string[-1-i] = string[-1-i], string[i]

(在PEP8样式指南中,下划线代替了letter。)

甚至更好:

string = string[::-1]

答案 1 :(得分:0)

我看到变量“ string”是字符串列表。您可以像这样简单地将其反转:

string = ['h', 'e', 'l', 'l', 'l', 'o']
string.reverse()
string

这应该打印['o', 'l', 'l', 'l', 'e', 'h']