简体   繁体   English

查找列表中最长的单词长度 Python

[英]Finding the longest length of word in the list Python

Can you help me understand how this code works?你能帮我理解这段代码是如何工作的吗?

words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
best = 0
for index in range(len(words)):
    if len(words[index]) > len(words[best]):
        best = index
print(words[best])

For every word in the list, check that, if the length of the current word is more than the longest word we have seen so far then it is the new longest word.对于列表中的每个单词,检查当前单词的长度是否大于我们目前看到的最长单词,那么它就是新的最长单词。

Basically, instead of storing the lengths of the words in a list, we are checking it every time & then determining the word, with the longest length.基本上,我们不是将单词的长度存储在列表中,而是每次都检查它,然后确定长度最长的单词。

Above code works like this上面的代码是这样工作的

  1. first Initialising best = 0首先初始化最佳 = 0
  2. Now iterating the for loop based on length of the list from 0 to 5 index ,现在根据从 0 到 5 索引的列表长度迭代 for 循环,
  3. if length of word for [0 ]index greater than Length of word index [best] means best will replace as current index,like that如果 [0] 索引的单词长度大于单词索引的长度 [best] 表示最好将替换为当前索引,就像这样
  4. process will goes on till the for loop end过程将一直持续到 for 循环结束
  5. At end print current best index value word最后打印当前最佳索引值字

We have this code:我们有这个代码:

words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
best = 0
for index in range(len(words)):
    if len(words[index]) > len(words[best]):
        best = index
print(words[best])

Let's break this down a bit:让我们把它分解一下:

words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]

This creates a list of words of various lengths.这将创建一个不同长度的单词列表。

best = 0

This variable holds the index to the word with the longest length we have encountered so far.这个变量保存了迄今为止我们遇到的最长单词的索引。

for index in range(len(words)):

The for statement will iterate through the list of words. for语句将遍历单词列表。

    if len(words[index]) > len(words[best]):

This if statement checks if the word at the current index is longer than the word at the index to which best points to.这个if语句检查当前索引处的单词是否比best指向的索引处的单词长。

        best = index

If the new word is longer than our best word so far, we set the best word to the new index.如果新词比我们目前最好的词长,我们将最好的词设置为新索引。

print(words[best])

We print the word by utilizing the saved best word index.我们使用保存的最佳单词索引打印单词。

best = 0 : best = 0

This means that, so far, the longest length in the list is 0. This value will be updated in the loop.这意味着,到目前为止,列表中的最长长度为 0。该值将在循环中更新。

for index in range(len(words)) : for index in range(len(words))

In your example, len(words) is 6, that is the number of words in your list 'words'.在您的示例中,len(words) 为 6,即列表“单词”中的单词数。 So the loop will go from index 0 ("dan") to 5 ("aaa").所以循环将从索引 0(“dan”)到 5(“aaa”)。

Then the program checks if the length of the current word is greater than the length of the longest word so far.然后程序检查当前单词的长度是否大于迄今为止最长单词的长度。 If it is longer, then you save the current index in the variable 'best'.如果它更长,则将当前索引保存在变量“best”中。

Finally, it prints the word corresponding to that index.最后,它打印与该索引对应的单词。

The for loop there iterates through the dynamically created list of indices from 0 to the length of words , which is 6. (range does not include the 6th index.)那里的for循环遍历动态创建的索引列表,从 0 到words的长度,即 6。(范围不包括第 6 个索引。)

Then if the length of the word that is in the index of value of the index is greater than the previously selected longest word, the new index of the longest word will be the current index.然后如果索引值的index中的单词的长度大于先前选择的最长单词,则最长单词的新索引将是当前索引。

Trace: best = 0 index = 0跟踪:最佳 = 0 索引 = 0

Is the length of the words[index] (dan) greater than the length of words[best] (dan)?单词[index] (dan) 的长度是否大于单词[best] (dan) 的长度? No. Proceed to next iteration.否。继续进行下一次迭代。

best = 0 index = 1最佳 = 0 指数 = 1

Is the length of the words[index] (kar) greater than the length of words[best] (dan)? words[index] (kar) 的长度是否大于 words[best] (dan) 的长度? No. Proceed to next iteration.否。继续进行下一次迭代。

best = 0 index = 2最佳 = 0 指数 = 2

Is the length of the words[index] (dream) greater than the length of words[best] (dan)?单词[index](dream)的长度是否大于单词[best](dan)的长度? Yes.是的。 The new value of best is 2. best 的新值是 2。

Then repeat the process until you finished executing the process然后重复这个过程,直到你完成这个过程

Your code is iterating over indices 0, 1, 2, ..., length-1 of list named words .您的代码正在迭代名为words的列表的索引0, 1, 2, ..., length-1

First time it is considering the max length string as the one which is at index 0 ie by setting best = 0 .第一次将最大长度字符串视为索引0处的字符串,即通过设置best = 0

In each iteration it is comparing the lengths of current string present at index best with string present at index index and resetting the value of rest with new index if condition len(words[index]) > len(words[best]) gets evaluated to True .在每次迭代中,它比较索引best处当前字符串的长度与索引index处出现的字符串,如果条件len(words[index]) > len(words[best])被评估为, rest用新索引重置rest的值True

In this way, after completion of for loop, you are getting an exact index of max length string.这样,在完成 for 循环后,您将获得最大长度字符串的精确索引。

So if your intension is to get max length, you can also calculate max length string and its length.因此,如果您的意图是获得最大长度,您还可以计算最大长度字符串及其长度。

Below is the single line of code using reduce() and lambda that you can use to get length of max length string available in list.下面是使用reduce()lambda的单行代码,您可以使用它们来获取列表中可用的最大长度字符串的长度。

>>> words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
>>> 
>>> reduce(lambda a, b: a if len(a) > len(b) else b, words)
'AHAHAHAHAHAHHHAAHAHA'
>>> 
>>> len(reduce(lambda a, b: a if len(a) > len(b) else b, words))
20
>>> 

There's already a number of good responses, but here's another using the lesser known key argument to max :已经有很多很好的回应,但这里有另一个使用鲜为人知的max key参数:

>>> words = ["dan","kar","dream","adsadsadad","AHAHAHAHAHAHHHAAHAHA","aaa"]
>>> max(words, key=len)
'AHAHAHAHAHAHHHAAHAHA'

Edit : I missed the comment from @Indominus in my initial response, so he should get all the credit :P编辑:我在最初的回复中错过了@Indominus 的评论,所以他应该得到所有的信任:P

It's nothing but 'Linear Search' algorithm.这只不过是“线性搜索”算法。

let's take the same example with not words but numbers.让我们举同样的例子,不是单词而是数字。

nums = [ 9,5,8,6,3,4 ]

#assuming the first element as our biggest number
biggest_number = nums[0]

for i in range(0, len(nums)):
  if nums[i] > biggest_number:  #comparing each number with the biggest number we assumed
    biggest_number = nums[i]   #if our current number bigger than biggest_number then replace the value

print(biggest_number)

In the code, you're just comparing elements one by one with all other elements and checking if the current element satisfies the condition, which in this case is whether it is bigger than others or not, and replacing the values where it does not;在代码中,您只是将元素与所有其他元素一一比较并检查当前元素是否满足条件,在这种情况下是它是否大于其他元素,并替换不满足的值; and finally returning the last value which satisfied the condition.最后返回满足条件的最后一个值。

In your code, it's about length of the string.在您的代码中,它与字符串的长度有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在列表python中找到最长的单词 - finding longest word in a list python 列表中最长单词的长度 - Length of longest word in a list 在不规则的列表列表中查找最长列表的长度 - Finding length of the longest list in an irregular list of lists Python MapReduce 长度最长的单词并显示最长的单词 - Python MapReduce length longest word and show longest word(s) Python 3.6.2 - 在子列表中查找最长字符串的长度并将该值存储在现有列表中 - Python 3.6.2 - Finding the length of the longest string in a sublist and store that value in an existing list Python:在列表中查找最小数的最长序列的长度时,输出不正确 - Python: Incorrect output while finding the length of the longest sequence of the minimum number in a list 找到最长的重复长度? - Finding the length of longest repeating? 找到最长子序列的长度 - finding the length of the longest subsequence python代码的时间复杂度,用于查找可以由列表中其他单词组成的最长单词(后续) - Time complexity of python code for finding the longest word that can be made of other words in the list (follow-up) python代码的时间复杂度,用于查找可以由列表中其他单词组成的最长单词 - Time complexity of python code for finding the longest word that can be made of other words in the list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM