【发布时间】: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