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

แปลงสมาชิกใน List of Tuples ให้เป็น Float ใน Python

วนลูปแต่ละ Tuple และแต่ละสมาชิก ใช้ isalpha() ตรวจสอบว่าเป็นตัวอักษร ถ้าไม่ใช่แปลงเป็น float

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

my_list = [("45", "Jane"), ("11", "Will"), ("37.68", "86.78"), ("Rob", "89.90")]
print("The list is : ")
print(my_list)

my_result = []
for tup in my_list:
    temp_val = []
    for elem in tup:
        if elem.isalpha():
            temp_val.append(elem)
        else:
            temp_val.append(float(elem))
    my_result.append((temp_val[0], temp_val[1]))

print("The float values are : ")
print(my_result)

ผลลัพธ์

The list is : [('45', 'Jane'), ('11', 'Will'), ('37.68', '86.78'), ('Rob', '89.90')]
The float values are : [(45.0, 'Jane'), (11.0, 'Will'), (37.68, 86.78), ('Rob', 89.9)]

คำอธิบาย

  • สร้าง List ใหม่เก็บผลลัพธ์
  • วนลูป Tuple และสมาชิกภายใน
  • isalpha() True = เก็บสตริงเดิม, False = แปลง float
  • สร้าง Tuple ใหม่จาก temp_val