涉及列表的for循环中的Python编程

时间:2016-11-04 00:59:26

标签: python python-3.x

这是我的代码:

import random   #Imports the random module

name = input("Enter your first name: ")   #Prompts the user to input their first name

name = name.capitalize()    #Capitalizes their first name

randomPhrase = ''   #For the random phrase to start out with being in a string

phrase = input("Enter a phrase containing characters a-z and/or 0-9: ")  #Prompts the user to input a phrase

phrase = phrase.lower() #automatically lowercases all characters in the phrase

phraseLength = len(phrase)  #Gets the length of the phrase the user inputs

phrase = [phrase]   #Converts phrase to a list

'print(phraseLength)' #This is to test to see if it correctly gets how long the phrase is

allowedChars = [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
                'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4',
                '5', '6', '7', '8', '9', '0']  #This will be the alphabet and numbers, which is allowed to be in the phrase

""""""
for x in phrase:    #This will go for however long the phrase is

    if x in allowedChars:   #This will tell if the user input phrase contains characters from alloweChars

        print("It works")   #Outputs this Works, mainly for testing reasons

    if x not in allowedChars:   #This will tell if the phrase does not contain any characters from allowedChars

        phrase = input("Enter another phrase: ")    #If the user doesn't have any chars from allowedChars, they input a new phrase


for i in range(0, phraseLength):    #This is to generate a random phrase that is the same length as the user phrase

    randomPhrase = randomPhrase + random.choice(allowedChars)   #Continually adds a new character from allowedChars to the randomPhrase

print(randomPhrase) #Spits out a random phrase the length of the phrase from the user

在第一个for循环中,我有两个if语句,如果用户在第一个短语中输入任何数字,它会直接跳转到第二个if语句,即使它在允许的字符列表中。我不确定为什么会一直这样。

4 个答案:

答案 0 :(得分:0)

可能有更好的方法。

import string
allowedChars = string.ascii_lowercase + string.digits + ' ' # 'abcdefghijklmnopqrstuvwxyz0123456789 '
randomPhrase = ''
name = input("Enter your first name: ")
name = name.capitalize()    #Capitalizes their first name
phrase = input("Enter a phrase containing characters a-z and/or 0-9: ")  #Prompts the user to input a phrase
while not phrase.replace(' ', '').isalnum():
    phrase = input("Enter another phrase: ")
for i in range(len(phrase)):    #This is to generate a random phrase that is the same length as the user phrase
    randomPhrase += random.choice(allowedChars)   #Continually adds a new character from allowedChars to the randomPhrase
print(randomPhrase)

String .isalnum()方法检查字符串是否仅包含字母数字字符。我已使用phrase.replace(' ', '')删除空格,因为它们在您的代码中是允许的。 while not phrase.replace(' ', '').isalnum()循环将一直运行,直到有人插入正确格式化的短语。

答案 1 :(得分:0)

我怀疑这段代码没有按你的想法行事:

var pagenoNodeList = doc.SelectNodes("Body/Context/PageNo");
var pageNoNode = pagenoNodeList[0]; // To select the first node
var text = pageNoNode.InnerText;    // Gets the text value inside the node
textBox1.Text = text;

通过将此打印代码添加到for循环中,您可以看到我的意思:

for x in phrase:    #This will go for however long the phrase is
    if x in allowedChars:   #This will tell if ...

产生的输出将是整个字符串,而不是单个字符。

因此,修复代码的第一步是更改此行:

print("x = {}".format(x))

对此:

phrase = [phrase]   #Converts phrase to a list

现在至少for循环将循环遍历字符串的字符。

答案 2 :(得分:0)

phrase = [phrase]没有按你的想法行事。它使用完整的短语作为单个元素制作单个元素list,而不是单个字符的list

这意味着第一个x是完整的phrase;它不仅仅是用户输入一个数字,它实际上是任何长度超过一个字符的输入都会导致测试失败(因为allowed中的所有条目都不长于长度1)

你可能打算做phrase = list(phrase),它会返回list个别字符。但你不需要这样做; str已经是他们角色的迭代(这就是list构造函数可以接受str的原因),而且你不会改变phrase,所以只是完全省略转换并迭代原始字符串。

正如另一个答案所指出的,这是一种缓慢而可怕的方法,但是我希望你理解为什么这没有用。

答案 3 :(得分:0)

问题在于:

词组= [词组]

您想要做什么将短语转换为列表是

phrase = list(短语)

当我以这种方式运行它时它起作用,虽然它打印“它有效”了很多次:)