Python ไม่มี scanf() เหมือน C แต่มีวิธีอ่านหลายค่าในบรรทัดเดียวได้ง่ายด้วย input() ร่วมกับ split(), map(), หรือ List Comprehension
วิธี 1: เรียก input() หลายครั้ง (ไม่แนะนำ)
>> x, y, z = input(), input(), input()
40 30 10
>>> x, y, z
('40', '30', '10')
ต้องกด Enter 3 ครั้ง ไม่สะดวก
วิธี 2: List Comprehension + split() (แนะนำ)
>> x, y, z = [int(x) for x in input().split()]
9 12 15
>>> x, y, z
(9, 12, 15)
# ถ้าอยากได้ string ปนตัวเลข
>>> x, y, z = [x for x in input().split()]
40 10 "hello"
>>> x, y, z
('40', '10', '"hello"')
วิธี 3: map() + split() (เร็วและ Pythonic)
>> x, y, z = map(int, input().split())
40 54 90
>>> x, y, z
(40, 54, 90)
การทำงานของ split()
>>> "9 12 15".split()
['9', '12', '15']
>>>> "40 10 hello".split()
['40', '10', 'hello']
split() แยกด้วย whitespace (space, tab, newline) เป็น list ของ string
สรุป
| วิธี | เหมาะกับ |
|---|---|
[int(x) for x in input().split()] | แปลงชนิดข้อมูลซับซ้อน, ต้องการ logic เพิ่ม |
map(int, input().split()) | แปลงชนิดข้อมูลเดียวกันทั้งหมด (เร็วที่สุด) |
[x for x in input().split()] | เก็บเป็น string ทั้งหมด |