เมื่อต้องการหาค่าเฉลี่ยจำนวนหลักตัวเลข (average digit count) ในลิสต์ สามารถใช้ลูป iteration, str() และตัวดำเนินการ / ได้
ตัวอย่าง
my_list = [324, 5345, 243, 746, 432, 463, 946787]
print("The list is :")
print(my_list)
sum_digits = 0
for ele in my_list:
sum_digits += len(str(ele))
my_result = sum_digits / len(my_list)
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [324, 5345, 243, 746, 432, 463, 946787] The result is : 3.5714285714285716
คำอธิบาย
กำหนดลิสต์ตัวเลขและแสดงผล
สร้างตัวแปร
sum_digits = 0สะสมจำนวนหลักวนลูปแต่ละตัวเลข แปลงเป็นสตริง หาความยาว
len(str(ele))บวกสะสมหารผลรวมด้วยจำนวนสมาชิกในลิสต์ได้ค่าเฉลี่ย
แสดงผลลัพธ์