Python 3.x 在集合上迭代时重复输出

Python 3.x 在集合上迭代时重复输出,python-3.x,intellij-idea,Python 3.x,Intellij Idea,当我迭代一组字母并删除另一组字母中包含的字母时,我很难理解为什么会收到重复输出 代码 例如: Please enter some text: camera ['c', 'm', 'r'] ['c', 'm', 'r'] 打印的次数与文本中非元音的次数相同 正确的方法 制作集合的副本或单独从文本创建集合 复制一套 new_set = old_set.copy() #and check the id() values for both here 单独从文本创建集合的步骤 input_ = inp

当我迭代一组字母并删除另一组字母中包含的字母时,我很难理解为什么会收到重复输出

代码

例如:

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

打印的次数与文本中非元音的次数相同

正确的方法 制作集合的副本或单独从文本创建集合

复制一套

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
一次性打印非元音的步骤 先前答案中的错误
  • 在迭代时删除元素。 .
  • 我将文本和新文本指向同一组。 我们可以通过“is”操作员确认这一点

    文本为新文本#返回真值

    print(id(text)),print(id(new_text))#具有相同的值,因此更改 一个改变另一个

  • 先前的回答(不正确)
    通过更改集合,输出如下所示

    text=input(“请输入一些文本:”).lower()
    元音={a”,“e”,“i”,“o”,“u”,“y”,“'}
    新建文本=设置(文本)
    对于文本中的t:
    如果元音中有t:
    新文本丢弃(t)
    
    打印(已排序(新文本))
    我正在尝试剪切双输出,即[c',m',r']这会产生运行时错误:在迭代过程中设置更改的大小我使用该代码修复了问题,但更改了:text=input(“请输入一些文本:”).lower():new_text=Set(text)@ChrisOlson我通过编辑解决方案添加了正确的答案。请检查一下。
    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 = 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))