Python 程式,從列表中列印母音最多的元素
當需要從列表中列印母音最多的元素時,會使用列表解析。
示例
下面對其進行演示
my_list = ["this", "week", "is", "going", "great"] print("The list is :") print(my_list) my_result = "" max_length = 0 for element in my_list: vowel_length = len([element for element in element if element in ['a', 'e', 'o', 'u', 'i']]) if vowel_length > max_length: max_length = vowel_length my_result = element print("The result is :") print(my_result)
輸出
The list is : ['this', 'week', 'is', 'going', 'great'] The result is : k
說明
- 定義字串列表,並顯示在控制檯上。
- 建立一個空的字串變數。
- 定義一個名為“max_length”的變數,並將其賦值為“0”。
- 對列表進行迭代,並使用列表解析檢查是否存在母音。
- 將其轉換為列表,並將其長度指定給變數。
- 如果此列表的長度大於“max_length”,則將它們等同。
- 將元素指定為輸出。
- 在控制檯上將其顯示為輸出。
廣告