【问题标题】:Extracting random characters from a string, then printing the remainder.从字符串中提取随机字符,然后打印剩余部分。
【发布时间】:2012-11-08 18:06:42
【问题描述】:

作为我大学课程的一部分,我正在学习 Python。我一直在尝试完成的一项任务是编写一个程序,该程序将打印出随机字母及其在“反建制主义”中的对应位置。然后它将剩余的字母打印在一行上。

我一直在尝试以一种可能是疯狂怪异的迂回方式来执行此操作 - 使用所选值填充列表并从原始值中删除这些字符。

我意识到我的程序可能全是错误和损坏的;我今天才开始学习列表!

import random
word = "antidisestablishmentarianism"
wordList =["antidisestablishmentarianism"]

print("The Word is:",word,"\n")

lengthWord = len(word)
usedValues=[]
for i in range(5):
    position = random.randrange(0,lengthWord)
    print("word[",position, "]\t", word [position])
    usedValues=[position]
for ch in wordList:
    wordList.remove([usedValues])
print("The remaining letters are",WordList, sep='')

【问题讨论】:

  • 提取出来的字符需要按顺序排列吗?

标签: python list random python-3.x


【解决方案1】:

我认为部分问题在于您错误地创建和操作了 worldListusedValues 列表。

要将字符列表创建为wordList,请使用list(word)。要将已使用的索引添加到 usedValues,请使用 usedValues.append(position)。还有一个问题是如何从单词列表中删除使用的值。

这是修复了这些错误的代码:

import random
word = "antidisestablishmentarianism"
wordList = list(word)

print("The Word is:",word,"\n")

lengthWord = len(word)
usedValues=[]
for i in range(5):
    position = random.randrange(0,lengthWord)
    print("word[",position, "]\t", word[position])
    usedValues.append(position)

for index in usedValues:
    wordList.pop(index)

print("The remaining letters are",WordList, sep='')

这将主要工作。但是,仍然存在逻辑错误。如果在第一个循环中两次获得相同的随机位置,则每次都会报告相同的字符。但是,当您稍后从列表中删除它们时,您最终会弹出两个不同的字母。同样,如果您从单词开头附近删除一个字母,您稍后删除的索引将不正确。如果最后选择的位置之一接近单词的末尾,您甚至可以获得IndexError

一个解决方法是在第一个循环中立即从列表中删除选定的值。您需要在每个循环中显式调用len(因为它每次都会更改),但除此之外一切都应该正常工作。

或者这是我解决问题的方法。我没有选择五个特定索引并将它们从列表中删除,而是 random.shuffle 列出所有索引并获取前五个。其余的可以按随机顺序打印出来,或者先排序,给人一种从原始单词中删除字母的印象。

import random
word = "antidisestablishmentarianism"

indexes = list(range(len(word)))
random.shuffle(indexes)

for i in indexes[:5]:
    print("word[%d] is '%s'" % (i, word[i]))

rest = sorted(indexes[5:]) # or just use indexes[5:] to keep random order
print("The remaining letters are '%s'" % "".join(word[i] for i in rest))

【讨论】:

    【解决方案2】:

    目前的代码存在一些问题。首先,这一行:

    wordList =["antidisestablishmentarianism"]
    

    并没有按照你的想法做 - 它实际上创建了一个包含单个项目 "antidisestablishmentarianism" 的列表。要将字符串转换为字符列表,您可以使用list() - 由于您已经拥有变量word,因此无需再次输入该单词。

    附带说明,wordList 不是一个很好的变量名。除了它使用 camelCase 而不是更 Pythonic 的下划线分隔样式这一事实之外,您在这里真正想要的是单词中的 字符 的列表。

    因此,该行可以替换为:

    characters = list(word)
    

    继续……这一行:

    lengthWord = len(word)
    

    是多余的 - 您只在代码中引用一次 lengthWord,因此您不妨在使用它的地方将该引用替换为 len(word)

    您的线路:

        usedValues=[position]
    

    也没有按照您的想法做:它完全替换 usedValues,列表中仅包含循环中的最新位置。要将值附加到列表,请使用list.append()

        used_positions.append(position)
    

    (我给变量取了一个更准确的名称)。你的下一个问题是这个块:

    for ch in wordList:
        wordList.remove([usedValues])
    

    首先,您确实想检查您之前存储的每个位置,而不是单词中的每个字符。您对list.remove() 的使用也是错误的:您不能像那样给出要删除的值列表,但是无论如何list.remove() 将从列表中删除值的第一个实例,而您要做的是删除item 在特定位置,这就是 list.pop() 的用途:

    for position in sorted(used_positions, reverse=True):
        characters.pop(position)
    

    我们使用了一个反向排序的used_positions 的副本,这样当我们删除一个项目时,used_positions 中的剩余位置不会滑出与characters[*] 的左侧对齐。

    你的最后一个问题是最后一行:

    print("The remaining letters are",WordList, sep='')
    

    如果您想打印以'' 分隔的列表的内容,这不是这样做的方法。相反,你需要str.join():

    print("The remaining letters are", "".join(characters))
    

    将所有这些更改付诸实践,并稍微整理一下,我们最终得到:

    import random
    word = "antidisestablishmentarianism"
    characters = list(word)
    
    print("The Word is:", word, "\n")
    
    used_positions = []
    
    for i in range(5):
        position = random.randrange(0, len(word))
        print("word[",position, "]\t", word[position])
        used_positions.append(position)
    
    for position in sorted(used_positions, reverse=True):
        characters.pop(position)
    
    print("The remaining letters are", "".join(characters))
    

    [*] 事实上,这引发了另一个问题:如果你的代码两次选择相同的位置怎么办?我会让你考虑那个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 2021-05-10
      • 2015-04-21
      相关资源
      最近更新 更多