In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how python deletes specific elements in the list". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "how to delete specific elements in the python list" can help you solve the problem.
The topics are as follows:
Given a string s that contains only uppercase and lowercase letters and spaces'', returns the length of its last word. If the string scrolls from left to right, the last word is the last word that appears.
If the last word does not exist, return 0.
Description: a word is the largest substring that consists of only letters and does not contain any space characters.
Example:
Enter: "Hello World"
Output: 5
Train of thought
The title is required to give a string, sline s, containing only letters and space characters, and to return the length of the last word. Consider the following points:
1. If s is an empty character, that is, s = "", 0 should be returned at this time.
2. If s contains only space characters, that is, s = "", it should also return 0 at this time.
3. If s contains both letters and spaces (or only letters), you can cut it with a space character through the split () function, so that you can get a list, which consists of only consecutive letters and empty characters, then delete all blank characters in the list, and finally return the length of the last item in the list.
So the question now is: how to delete a specific element in a list, in this case, to delete the empty characters in the list, that is, ""
Method 1
With the help of a temporary list, extract the non-empty elements into the temporary list, then take out the last item of the temporary list and return its length.
This is the stupidest approach, and the most time-consuming at run time:
Class Solution (object): def lengthOfLastWord (self, s): "": type s: str:rtype: int "if s.isspace (): # determines whether s consists only of space characters, such as slots ="return 0elif slots =": # to determine whether s is an empty string, such as slots ="return 0else: # if s is not empty and is not entirely composed of spaces temp = s.split (") # through the split method Cut the string s with a space character to get a list of words and empty strings, assign the list to tempnew = [] # to define an empty list, as an intermediate variable for t in temp: # iterate through temp, extract non-empty elements into new, and finally return the length of the last item of new to if t! = ": new.append (t) return len (new [- 1])
Before talking about method 2, say a wrong method: use the for loop, traverse the list forward, and delete the empty characters
As follows:
S = ["", "", "a", ""] for i in range (0Len (s)): if s [I] = "": del s [I] print (s)
If you run the above code, you will get an error:
The reason is that when an empty character is encountered, the length of the list becomes smaller after the empty character is deleted, but when it is iterated, it is traversed according to the original length, resulting in an overflow.
In addition, there is another drawback: some null characters may be omitted, because when the preceding null characters are deleted, the subsequent elements move forward in turn, causing the index to change with the corresponding value.
As follows:
B = [",", "a", ""] for i in range (0Len (b)): if I > = len (b): # add a judgment, when I is greater than the length of the list, jump out of the loop to avoid error breakif b [I] = ": del b [I] print (b)
So until we solve this problem, we can't use the for loop to traverse the list forward.
Method 2: use the while loop
Because the for loop cannot achieve its purpose, consider using the while loop, as follows:
Class Solution (object): def lengthOfLastWord (self, s): "": type s: str:rtype: int "if s.isspace (): # determines whether s consists only of space characters, such as slots ="return 0elif slots =": # to determine whether s is an empty string, such as slots ="return 0else: # if s is not empty and is not entirely composed of spaces temp = s.split (") # through the split method Cut the string s with a space character to get a list of words and empty strings, assign the list to tempi = 0 # and set the initial pointer to 0while I
< len(temp): # 使用while循环,当指针i的值小于列表temp的长度时,则一直循环if temp[i] == "": # 从索引0开始,如果temp[i]为空del temp[i] # 则删除该索引对应的值,也就是删除temp[i]i -=1 # 删除之后,由于列表整体长度变小了1位(也就是后面的元素都往前提了一位),所以索引i需要减1,以便下次遍历时不丢掉挨着的元素i += 1 # 判断完索引i后,给索引自增1,进行下一轮判断return len(temp[-1]) # temp所有元素遍历完成后,就剔除了所有空字符串,取出最后一项的长度返回即可方法3:for循环倒序删除空字符串 刚才说了使用for循环时,正向遍历会导致溢出或者结果出错,但是从后向前遍历是可以的 class Solution(object):def lengthOfLastWord(self, s):"""倒序循环删除空字符串:type s: str:rtype: int"""if s.isspace(): # 判断s是否只由空格字符组成,如s==" "return 0elif s == "": # 判断s是否为空字符串,如s==""return 0else: # 如果s不为空,且不全是由空格组成temp = s.split(" ") # 通过split方法,用一个空格字符将字符串s进行切割,可以得到由单词和空字符串组成的列表,将列表赋给tempfor i in range(len(temp)-1, -1, -1): # 倒序循环删除空字符串if temp[i] == "":del temp[i]return len(temp[-1])方法4:拷贝原列表 拷贝原列表,然后遍历拷贝的列表来找出空字符,最后再原列表中删除空字符 '''学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!'''class Solution(object):def lengthOfLastWord_3(self, s):""":type s: str:rtype: int"""if s.isspace(): # 判断s是否只由空格字符组成,如s==" ",用isspace()函数判断return 0elif s == "": # 判断s是否为空字符串,如s==""return 0else: # 如果s不为空,且不全是由空格组成temp = s.split(" ") # 通过split方法,用一个空格字符将字符串s进行切割,可以得到由单词和空字符串组成的列表,将列表赋给tempfor i in temp[:]: # temp[:]是对原始的temp的一个拷贝,是一个新的list,所以,我们遍历新的list,而删除原始的list中的元素if i == "":temp.remove(i)return len(temp[-1]) 这样理解一下:假如有一个列表s = [1,1,2,3,4,4,3,1],现在要把里面的1都删掉 我们先拷贝s,得到一个新列表(注意不能用一个变量直接等于s,如a=s,其实a和s都指向同一个列表,本质还是一个),新列表的元素与原列表完全相同 然后遍历新列表,当遇到某个元素的值为1时,就在原列表中把这个元素删掉(使用列表的remove方法删除),因为remove在删除元素时,只会删掉遇到的第一个目标元素,所以我们继续遍历新列表,如果再遇到1,就继续在原列表中删除, 最终遍历完新列表,也就会在原列表中把所有1都删掉了 上述代码中的temp[:]是拷贝原列表得到新列表的一个方法,也可以通过如下方法复制得到一个新列表 >> > new_temp = temp [:] > > new_temp = list (temp) > new_temp = temp*1 > import copy > new_temp = copy.copy (temp) about "how python deletes specific elements in the list" ends here. Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.