简体   繁体   English

检查多个列表的最后一个元素

[英]Checking the last element of multiple lists

How can i check the last letter in a string that is the last element of multiple lists?如何检查作为多个列表的最后一个元素的字符串中的最后一个字母? I want to see if the last element of eight different lists are the same, if they are not i want to throw out an error and let the user try again.我想看看八个不同列表的最后一个元素是否相同,如果不是,我想抛出一个错误并让用户再试一次。 The point of the function i want to make is that if there are no lists with this last element the function should print something like ("Does not") As you can see in the example this should work because e is present as the last element in "Tie" and "he".我要说明的 function 的要点是,如果没有包含最后一个元素的列表,则 function 应该打印类似 ("Does not") 如您在示例中看到的那样,这应该有效,因为 e 作为最后一个元素存在在“领带”和“他”中。

pile1=["vapor","Tie"]
pile2=["stone","he"]
pile3=["glass","sto"]

piles=pile1,pile2,pile3
def lose():
    for pile in piles:
        #here it should go through the last element and last letter in the string of everything in bunke
            print("Does not work")
lose()


  

Build a list of all last letter of all last word of each pile then create a set with this list.建立每个堆的所有最后一个单词的所有最后一个字母的列表,然后用这个列表创建一个set Now, if the length of this set is not 1 there are, at least, two different letters:现在,如果这个set的长度不是 1,那么至少有两个不同的字母:

if len(set([pile[-1][-1] for pile in piles if len(pile)])) > 1:
    print('Does not')

# Output:
Does not

In your example:在您的示例中:

>>> [pile[-1][-1] for pile in piles if len(pile)]
['e', 'e', 'o']

>>> set([pile[-1][-1] for pile in piles if len(pile)])
{'e', 'o'}

Slicing!切片! This refers to the indexing of characters这是指字符的索引

String, technically, is a list of characters.从技术上讲,字符串是一个字符列表。 So this works not only for accessing whole elements of lists, but characters of String.所以这不仅适用于访问列表的整个元素,而且适用于字符串的字符。

Try out this code and see what it gives you.试试这个代码,看看它给了你什么。 You may need to alter it, if I have misunderstood the specifics.如果我误解了细节,您可能需要更改它。

for pile in piles:
    print(pile[-1][-1])

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM