Python for 循环到 while 循环获取唯一值

Python for loop to while loop for unique value

string = "Python, program!"

result = []
for x in string:
    if x not in result and x.isalnum():
        result.append(x)
print(result)

这个程序使得如果一个重复的字母在一个字符串中被使用了两次,它只会在列表中出现一次。在这种情况下,字符串“Hello, world!”将显示为

['H', 'e', 'l', 'o', 'w', 'r', 'd']

我的问题是,如何使用 while 循环而不是 for 循环来获得相同的结果?我知道真的没有必要把一个完美的 for 循环改成 while 循环,但我还是想知道。

这是一种可以在 while 循环中完成的方法:

text = "Python, program!"

text = text[::-1]  # Reverse string
result = []
while text:
    if text[-1] not in result:
        result.append(text[-1])
    text = text[:-1]

print(result)

有几种方法可以做到这一点。

模拟 for 循环

这就是 for 循环在幕后所做的事情:

it = iter(string)
while True:
    try:
        # attempt to get next element
        x = next(it)
    except StopIteration:
        # no next element => get out of the loop
        break

    if x not in result and x.isalnum():
        result.append(x)

C 方式

您可以简单地索引到您的字符串中:

i = 0
while i < len(string):
    x = string[i]
    if x not in result and x.isalnum():
        result.append(x)

    i += 1

这类似于在 C 语言中迭代容器的方式 - 通过对其进行索引并随后递增索引:

for (int i = 0; i < strlen(string); i++)
    printf("%c", string[i]);

但是,索引并不总是有效,因为一些可以迭代的对象不支持索引:

a_generator = (i for i in range(5))
for elem in a_generator:
    print(a) # works fine

a_generator = (i for i in range(5))
a_generator[0]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable