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

แปลงพิกัดตำแหน่ง (Coordinates) เป็น Tuple ใน Python

บทนำ

การแปลงสตริงที่เก็บพิกัด เช่น "67.5378, -78.8523" ให้กลายเป็น tuple ของตัวเลข ทำได้โดยใช้ฟังก์ชัน eval() ซึ่งจะประเมินสตริงเป็นโค้ด Python

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

coord_str = "67.5378, -78.8523"
print("สตริงพิกัด:", coord_str)

# ใช้ eval แปลงสตริงเป็น tuple
coord_tuple = eval(coord_str)

print("Tuple พิกัด:", coord_tuple)
print("ชนิดข้อมูล:", type(coord_tuple))
print("Latitude:", coord_tuple[0])
print("Longitude:", coord_tuple[1])

ผลลัพธ์

สตริงพิกัด: 67.5378, -78.8523
Tuple พิกัด: (67.5378, -78.8523)
ชนิดข้อมูล: <class 'tuple'>
Latitude: 67.5378
Longitude: -78.8523

คำอธิบาย

  • eval("67.5378, -78.8523") ตีความสตริงเป็น tuple literal ของ Python
  • ได้ tuple ของ float 2 ค่า (latitude, longitude)

⚠️ คำเตือนความปลอดภัย

eval() อันตรายหากใช้กับข้อมูลจากผู้ใช้หรือแหล่งที่ไมเชื่อถือได้ เพราะสามารถรันโค้ด bấtได้

วิธีปลอดภัยกว่า: ใช้ split และ float

coord_str = "67.5378, -78.8523"
lat_str, lon_str = coord_str.split(',')
coord_tuple = (float(lat_str.strip()), float(lon_str.strip()))
print(coord_tuple)  # (67.5378, -78.8523)

วิธีนี้ปลอดภัยกว่าและควรใช้แทน eval() ในโปรดักชัน