当我迭代一组字母并删除另一组中包含的字母时,我无法理解为什么我会收到重复输出。
代码
text = set(input("Please enter some text: ").lower())
vowels = {"a", "e", "i", "o", "u", "y", ' '}
for t in text:
if t in vowels:
new_text = (text-vowels)
print(sorted(new_text))
示例:
Please enter some text: camera
['c', 'm', 'r']
['c', 'm', 'r']
答案 0 :(得分:-1)
打印的次数与文本中非元音的次数相同。
制作该集的副本或单独从文本创建集。
制作套装
的副本new_set = old_set.copy() #and check the id() values for both here
单独从文本创建一个集
input_ = input("Please enter some text: ").lower()
text = set(input_)
vowels = {"a", "e", "i", "o", "u", "y", ' '}
#To remove the vowel one-by-one by iterating
new_text = set(input_)
for t in text:
if t in vowels:
new_text.discard(t) # or remove
print(sorted(new_text))
我将text和new_text指向同一个集合。 我们可以通过'is'运算符来确认。
text is new_text #Returns True
print(id(text)),print(id(new_text))#具有相同的值,因此更改 一个改变另一个
text = set(input("Please enter some text: ").lower())
vowels = {"a", "e", "i", "o", "u", "y", ' '}
#To remove the vowel one-by-one by iterating
new_text = text
for t in text:
if t in vowels:
new_text.discard(t) # or remove
#To print the non-vowels at one-go
print(sorted(new_text))
答案 1 :(得分:-1)
通过更改集合,输出的工作方式如下......
text = input("Please enter some text: ").lower()
vowels = {"a", "e", "i", "o", "u", "y", ' '}
new_text = set(text)
for t in text:
if t in vowels:
new_text.discard(t)
print(sorted(new_text))

...输出
Please enter some text: camera
['c', 'm', 'r']