【问题标题】:Why are these loop outputs different?为什么这些循环输出不同?
【发布时间】:2021-02-18 16:24:45
【问题描述】:

我正在处理一项任务,我需要对字符串中的重复字母进行排序和删除。我最终得到了这个函数做我想做的事,但运气不好。我不知道为什么这些代码行会产生不同的输出。有人可以帮我理解吗?

def format_string(string1):
    sorted1 = sorted(string1)
    print(sorted1)

    i = 0
    while i < len(sorted1) - 1:
        if sorted1[i] == sorted1[i + 1]:
            del sorted1[i + 1]
        else:
            i += 1
    return sorted1


print(format_string("aretheyhere"))

['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']

['a', 'e', 'h', 'r', 't', 'y']

#这就是我想要的。但这些看似相似的线条却没有。

def format_string(string1):
    sorted1 = sorted(string1)
    print(sorted1)

    i = 0
    j = i + 1
    while i < len(sorted1) - 1:
        if sorted1[i] == sorted1[j]:
            del sorted1[j]
        else:
            i += 1
    return sorted1


print(format_string("aretheyhere"))

['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']

['a', 'y']

def format_string(string1):
    sorted1 = sorted(string1)
    print(sorted1)

    i = 0
    while i < len(sorted1) - 1:
        if sorted1[i] == sorted1[i + 1]:
            del sorted1[i + 1]
        i += 1
    return sorted1


print(format_string("aretheyhere"))

['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']

['a', 'e', 'e', 'h', 'r', 't', 'y']

改变输出的关键区别是什么?

【问题讨论】:

  • 你应该使用 for 循环而不是 while 循环,仅供参考
  • @Seth 您无法使用 for 循环遍历您正在修改的列表,因此这是对 while 循环的合理使用。
  • 问题是你没有更新j
  • @TedKleinBergman 你可以这样做:for i, _ in enumerate(sorted1):,这会更 Pythonic
  • @Seth 不,你不能,因为循环体正在从sorted1 中删除条目,从而使迭代器无效。

标签: python python-3.x loops


【解决方案1】:

变量j 不会增加,因为它没有在您的while 循环内更新,即在将j 的值设置为i+1 之后更改i 的值不会改变j 的值.例如,此函数将给出与第一个函数相同的结果,因为 j 的值在 while 循环内更新:

def format_string(string1):
    sorted1 = sorted(string1)
    print(sorted1)

    i = 0
    while i < len(sorted1) - 1:
        j = i + 1
        if sorted1[i] == sorted1[j]:
            del sorted1[j]
        else:
            i += 1
    return sorted1


print(format_string("aretheyhere"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 2018-01-14
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2022-08-02
    相关资源
    最近更新 更多