如何檢查作為多個串列最后一個元素的字串中的最后一個字母?我想看看八個不同串列的最后一個元素是否相同,如果不是,我想拋出一個錯誤并讓用戶重試。我想要創建的函式的重點是,如果沒有包含最后一個元素的串列,該函式應該列印類似 ("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()
uj5u.com熱心網友回復:
建立每堆最后一個單詞的所有最后一個字母的串列,然后set用這個串列創建一個。現在,如果 this 的長度set不是 1,那么至少有兩個不同的字母:
if len(set([pile[-1][-1] for pile in piles if len(pile)])) > 1:
print('Does not')
# Output:
Does not
在你的例子中:
>>> [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'}
uj5u.com熱心網友回復:
切片!這是指字符的索引
從技術上講,字串是一個字串列。所以這不僅適用于訪問串列的整個元素,還適用于訪問字串的字符。
試試這個代碼,看看它給了你什么。如果我誤解了細節,您可能需要更改它。
for pile in piles:
print(pile[-1][-1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370230.html
上一篇:在不匯入任何模塊的情況下,查找串列中相同數字的最大連續出現
下一篇:Pythondef函式賦值問題
