【发布时间】:2021-01-18 03:55:58
【问题描述】:
目标是将以下 for 循环转换为嵌套的理解列表。
txt=['-100:200','-15:0','0:15','30:45']
all_t=[]
for t in txt:
all_t.append([int ( idx ) for idx in t.split(":")])
进入
all_t=[int(idx) for idx in t.split(":") for t in txt]
但是,编译器返回错误
NameError: name 't' is not defined
感谢有关此错误的任何帮助
【问题讨论】:
-
改为写
for t in txt for idx in t.split(":")。编写循环的顺序与编写常规嵌套for循环的顺序相同。 -
@kaya3 赞成,但这会给
[-100, 200, -15, 0, 0, 15, 30, 45]而不是[[-100, 200], [-15, 0], [0, 15], [30, 45]]第二个想法...