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

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

ได้ลิสต์ที่สมาชิกเป็นสตริงตัวเลข ต้องการแปลงเป็นจำนวนเต็มเพื่อคำนวณต่อ

ใช้ int ใน list comprehension

Nested loops แปลงแต่ละสตริงในแต่ละ sublist

ตัวอย่าง

listA = [['29','12'], ['25'], ['70']]
print("Given list A: ", listA)
res = [[int(n) for n in element] for i in listA for element in i]
print("The numeric lists: ", res)

ผลลัพธ์

Given list A: [['29', '12'], ['25'], ['70']]
The numeric lists: [[2, 9], [1, 2], [2, 5], [7, 0]]

ใช้ map

map(int, list(elem[0])) สำหรับแต่ละ elem (สมาชิกเป็นลิสต์ที่มีสตริง 1 ตัว)

ตัวอย่าง

listA = [['29'], ['25'], ['70']]
print("Given list A: ", listA)
res = [list(map(int, list(elem[0]))) for elem in listA if elem]
print("The numeric lists: ", res)

ผลลัพธ์

Given list A: [['29'], ['25'], ['70']]
The numeric lists: [[2, 9], [2, 5], [7, 0]]