เมื่อจำเป็นต้องอ่านรายการคำและคืนค่าความยาวของรายการที่ยาวที่สุด วิธีหนึ่งสามารถกำหนดได้ว่าจะวนซ้ำในรายการและรับความยาวของทุกสตริงในรายการสตริงโดยใช้วิธี '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'
-
ใช้รายการสตริงเป็นพารามิเตอร์
-
รายการมีการวนซ้ำ และความยาวของทุกสตริงในรายการจะถูกกำหนด
-
ค่าที่ใหญ่ที่สุดจะถูกกำหนดและส่งคืนเป็นเอาต์พุต
-
รายการสตริงถูกกำหนดและแสดงบนคอนโซล
-
วิธีการนี้เรียกว่าการข้ามรายการนี้เป็นพารามิเตอร์
-
เอาต์พุตจะแสดงบนคอนโซล