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

Converting All Strings in List to Integers ใน Python

ได้ลิสต์ที่สมาชิกเป็นสตริงตัวเลข (เช่น ['5', '2', '-43', '23']) แปลงเป็นลิสต์ของ Integer จริง

วิธี 1: List Comprehension กับ int()


listA = ['5', '2', '-43', '23']
res = [int(x) for x in listA]
print(res)  # [5, 2, -43, 23]

วิธี 2: ใช้ map(int, list)


listA = ['5', '2', '-43', '23']
res = list(map(int, listA))
print(res)  # [5, 2, -43, 23]

สรุป

ทั้งคู่เทียบเท่า map เร็วกว่าเล็กน้อยสำหรับข้อมูลมาก list comprehension อ่านง่ายกว่าและ Pythonic กว่า