Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用while循环循环存储在my#u列表中的单词列表,并打印第一个字母为';A';或';a';_Python - Fatal编程技术网

Python 使用while循环循环存储在my#u列表中的单词列表,并打印第一个字母为';A';或';a';

Python 使用while循环循环存储在my#u列表中的单词列表,并打印第一个字母为';A';或';a';,python,Python,文本是不言自明的,我已经用for循环完成了它,但没有用while循环。 我只是不想要答案,我其实想知道怎么做。 非常感谢 ## A list of words is already stored in my_list for you ## to use to test your program, but your program must be ## written so as to work with whatever list of words is ## stored in my_list

文本是不言自明的,我已经用for循环完成了它,但没有用while循环。 我只是不想要答案,我其实想知道怎么做。 非常感谢

## A list of words is already stored in my_list for you
## to use to test your program, but your program must be
## written so as to work with whatever list of words is
## stored in my_list. You must use a loop, not separate
## print statements.
##
## For the list of words currently stored in my_list your printout should look like this:
##    k
##    e
##    t

my_list = ['petunia', 'Aardvark', 'elephant', 'apple', 'ant', 'monarch', 'eagle', 'tiger']



如果使用while循环,则需要创建一个设置为0的索引变量。然后,您将使用该索引遍历列表,直到到达列表的末尾,该列表的长度减去1。其余的逻辑与for循环类似

words = ["zero", "one", "two", "three"]

index = 0
while (index < len(words)):
    print(words[index])
    index += 1
words=[“零”、“一”、“二”、“三”]
索引=0
而(索引

要直接回答您的问题,您必须在while循环外创建一个设置为0的新变量,并在每次运行while循环时将该变量的值增加1。然后,使用该变量循环遍历my_列表的每个索引。例如:

x = 0 # Here is where we define the new variable
while (x < len(my_list)):
    if (my_list[x][0].lower() == "a"):
        print(my_list[x][-1]) 
    x += 1 # This is where we add 1 to its value at the end of the loop
x=0#这里是我们定义新变量的地方
而(x
首先,我们将x设为0,这样我们从我的列表的第一个索引开始。然后,我们执行while循环,以在my_列表的每个索引中保持循环(
len(my_列表)
返回my_列表的长度)。然后,我们测试my_数组索引x处字符串的第一个字符的小写版本是否等于“a”(我们使用小写以简化需要执行的测试数量)。然后,如果这是真的,我们在索引x处打印my_列表中字符串的最后一个字符(创建一个以-1开头的substr将获取字符串的最后一个字符,因此您不必担心获取大小和全部)。最后,我们将1添加到x以继续循环。这与for循环基本相同,只是有额外的步骤。所以,除非您需要使用while循环,否则我建议您还是使用for循环


我们必须创建这样的变量,因为(据我所知)没有其他方法可以遍历我的_列表的每个索引。希望这有帮助

对不起,我对python很陌生,你介意给我举个例子吗<代码>我列表中的单词:如果len(word)=:break print(word)
Welp,则无法在注释中设置格式,但正如您所看到的,我甚至弄乱了我的for循环。我已经更新了我的答案。另外,这是您的for循环解决方案吗?如果是这样,则中断是多余的。当我的_列表中的所有单词都用尽时,for循环将停止。啊,这就是让我发疯的原因!我试着不间断地做它,它会给我想要的(不是用当前的代码),然后我想用break重新做它(我不知道我不能用它),但它不起作用!我会坚持我当时做的第一件事!非常感谢你!谢谢你的回答!这消除了我在做(索引