Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.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 3.x 一个简单的基本Python问题,我不知道';我不明白_Python 3.x_For Loop_Arraylist - Fatal编程技术网

Python 3.x 一个简单的基本Python问题,我不知道';我不明白

Python 3.x 一个简单的基本Python问题,我不知道';我不明白,python-3.x,for-loop,arraylist,Python 3.x,For Loop,Arraylist,问题: def longestWord(listOfWords): biggestWord = listOfWords[0] biggestNum = len(biggestWord) for word in listOfWords: num = len(word) if num>biggestNum: biggestNum=num biggestWord=word return

问题:

def longestWord(listOfWords):
    biggestWord = listOfWords[0]
    biggestNum = len(biggestWord)
    for word in listOfWords:
        num = len(word)
        if num>biggestNum:
            biggestNum=num
            biggestWord=word
    return biggestWord

print(longestWord(["Hello", "Goodbye"]))
填写Python3函数longestWord的函数体(函数头应该保持原样)

函数接受一个输入参数,我们假设它是一个字符串列表,每个字符串构成一个英语单词。输出应该是列表中字母数最多的单词

必须使用for循环来编写此函数

回答:

def longestWord(listOfWords):
    biggestWord = listOfWords[0]
    biggestNum = len(biggestWord)
    for word in listOfWords:
        num = len(word)
        if num>biggestNum:
            biggestNum=num
            biggestWord=word
    return biggestWord

print(longestWord(["Hello", "Goodbye"]))

我理解前三行。它获取列表中的第一个值并保存输入单词的长度。但是,我不理解代码的其余部分。它如何比较两个输入的单词以输出最长的单词。什么是数字和单词?。多谢各位biggestWord的变量中。并将
biggestWord
的长度存储在名为
biggestNum
的变量中。然后,对于
listOfWords
中的每个单词,它将单词存储在名为
word
的变量中,并在名为
num
的变量中对其长度进行排序。然后比较
num
biggestNum
。如果某个单词的长度,即
num
大于到目前为止的最大长度,即
biggestNum
,则它会将
num
放入
biggestNum
中,以指示这是到目前为止的最大数字。并将
word
放入
biggestWord
替换旧单词。然后返回长度最大的单词,即
biggestWord

,这看起来像是一个Python问题。为什么它被标记为“C++”,为什么它在标题中称为C++而不是Python?这里没有C++,欢迎来到这里。请始终使用一个问题标题,用几个词来描述您的问题或问题,而不是说“我有一个问题…”,这样这里的专家就可以更容易地找到他们可以通过阅读标题回答的问题。THX:-我错误地输入了C++。SorrySorry,我不知道C++来自哪里,我是说Python 3。这句话让我对单词列表中的单词感到困惑:“我认为单词是一个函数。我上了一堂关于循环的课,现在我明白了。非常感谢。