我正在学习,我想找到一种更有效或更优雅(更短)的方法来实现相同目的:
list1 = [['-0.02', 'AAA'], ['-0.20', 'BBB'], ['0.10', 'CCC'], ['0.05', 'DDD']]
def convert_first_element_to_float(lst):
ls_a = []
ls_b = []
for el_a, el_b in lst:
ls_a.append(float(el_a))
ls_b.append(el_b)
return [list(a) for a in zip(ls_a, ls_b)]
result = convert_first_element_to_float(list1)
结果是:
[[-0.02, 'AAA'], [-0.2, 'BBB'], [0.1, 'CCC'], [0.05, 'DDD']]
答案 0 :(得分:2)
list comprehension可能是一种更优雅的方式:
>>> result = [[float(i), j] for i, j in list1]
>>> result
[[-0.02, 'AAA'], [-0.2, 'BBB'], [0.1, 'CCC'], [0.05, 'DDD']]
尽管它是operationally very similar,但它可能会导致性能略有改善,并且就代码行而言通常更为简洁。
for i, j
部分从list1
的每个子列表中解压缩每对元素。