Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แปลง Tuple เป็นค่า Float ใน Python

บทนำ

การแปลง tuple ของตัวเลข 2 ค่า ให้กลายเป็นทศนิยม (float) โดยนำค่าแรกเป็นส่วนเต็ม ค่าที่สองเป็นส่วนทศนิยม สามารถทำได้ด้วย join() และ float()

ตัวอย่างโค้ด

my_tuple = (7, 8)
print("Tuple:", my_tuple)

# รวมด้วยจุดทศนิยม แล้วแปลงเป็น float
result = float('.'.join(str(x) for x in my_tuple))

print("ค่า Float:", result)

ผลลัพธ์

Tuple: (7, 8)
ค่า Float: 7.8

คำอธิบาย

  • str(x) for x in my_tuple แปลงแต่ละตัวเป็นสตริง
  • '.'.join(...) รวมด้วยจุด "." → "7.8"
  • float(...) แปลงสตริงเป็น float

ข้อจำกัด

  • ทำงานได้ดีกับ tuple 2 element (integer part, fractional part)
  • ถ้า tuple มีมากกว่า 2 ค่า จะได้ float แปลก เช่น (1,2,3) → "1.2.3" → Error
  • ค่าส่วนทศนิยมต้องไม่มี leading zeros ที่สำคัญ (8 → .8 ไม่ใช่ .08)

เวอร์ชันรองรับหลายหลักทศนิยม

def tuple_to_float(tup):
    """แปลง tuple (integer_part, fractional_part) เป็น float"""
    if len(tup) != 2:
        raise ValueError("ต้องมี 2 element เท่านั้น")
    integer_part, fractional_part = tup
    # จัดการ leading zeros ใน fractional part
    frac_str = str(fractional_part)
    return float(f"{integer_part}.{frac_str}")

print(tuple_to_float((7, 8)))    # 7.8
print(tuple_to_float((12, 34)))  # 12.34
print(tuple_to_float((0, 5)))    # 0.5