保留列表中的所有值:
t = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
t = [int(v) if v.lstrip('-').isnumeric() else v for v in t]
print(t)
# output
[5, 12, 4, 3, 5, 14, 16, -2, 4, 'test']
删除非数字值:
t = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
t = [int(v) for v in t if v.lstrip('-').isnumeric()]
print(t)
# output
[5, 12, 4, 3, 5, 14, 16, -2, 4]
嵌套列表:
t = [['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test'] for _ in range(3)]
t = [[int(v) if v.lstrip('-').isnumeric() else v for v in x] for x in t]
print(t)
# output
[[5, 12, 4, 3, 5, 14, 16, -2, 4, 'test'],
[5, 12, 4, 3, 5, 14, 16, -2, 4, 'test'],
[5, 12, 4, 3, 5, 14, 16, -2, 4, 'test']]