ภาพรวม
เมื่อต้องการอ่าน List ของคำและคืนความยาวของคำที่ยาวที่สุด สามารถนิยามเมธอด วนลูปผ่าน List หาความยาวของทุก String ใน List ของ String ด้วยเมธอด len()
ตัวอย่างโค้ด
def longest_length_string(my_string):
len_str = len(my_string[0])
temp_val = my_string[0]
for i in my_string:
if(len(i) > len_str):
len_str = len(i)
temp_val = i
print("The word with the longest length is:", temp_val, " and length is ", len_str)
my_string = ["three", "Jane", "quick", "lesson", 'London', 'newyork']
print("The list is :")
print(my_string)
print("The method to find the longest string in the list is called")
longest_length_string(my_string)
ผลลัพธ์ตัวอย่าง
The list is : ['three', 'Jane', 'quick', 'lesson', 'London', 'newyork'] The method to find the longest string in the list is called The word with the longest length is: newyork and length is 7
คำอธิบาย
- นิยามเมธอด
longest_length_string - รับ List ของ String เป็นพารามิเตอร์
- วนลูป List หาความยาวของทุก String ใน List
- หาค่ามากที่สุดและคืนค่าเป็น Output
- นิยาม List ของ String แสดงบนคอนโซล
- เรียกเมธอดส่ง List นี้เป็นพารามิเตอร์
- แสดงผลลัพธ์บนคอนโซล