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

แปลงลิสต์ของสตริงตัวเลขเป็นลิสต์จำนวนเต็มเรียงลำดับใน Python

ได้ลิสต์ที่สมาชิกเป็นสตริงตัวเลข (รวมลบได้) ต้องการแปลงเป็น int แล้วเรียงลำดับ

ใช้ map และ sorted

map(int, listA) แล้ว sorted()

ตัวอย่าง

listA = ['54', '21', '-10', '92', '5']
print("Given list : \n", listA)
listint = map(int, listA)
res = sorted(listint)
print("Sorted list of integers: \n", res)

ผลลัพธ์

Given list : ['54', '21', '-10', '92', '5']
Sorted list of integers: [-10, 5, 21, 54, 92]

ใช้ int และ sort

list comprehension แปลงเป็น int แล้ว .sort()

ตัวอย่าง

listA = ['54', '21', '-10', '92', '5']
print("Given list : \n", listA)
res = [int(x) for x in listA]
res.sort()
print("Sorted list of integers: \n", res)

ผลลัพธ์

Given list : ['54', '21', '-10', '92', '5']
Sorted list of integers: [-10, 5, 21, 54, 92]

ใช้ sorted และ int ใน expression เดียว

sorted(int(x) for x in listA)

ตัวอย่าง

listA = ['54', '21', '-10', '92', '5']
print("Given list : \n", listA)
res = sorted(int(x) for x in listA)
print("Sorted list of integers: \n", res)

ผลลัพธ์

Given list : ['54', '21', '-10', '92', '5']
Sorted list of integers: [-10, 5, 21, 54, 92]