【问题标题】:NameError in nested list comprehension with Python使用 Python 的嵌套列表理解中的 NameError
【发布时间】: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]] 第二个想法...

标签: python list-comprehension


【解决方案1】:
txt=['-100:200','-15:0','0:15','30:45']
all_t=[[int(idx) for idx in t.split(":")] for t in txt]
print(all_t)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 2021-02-13
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    相关资源
    最近更新 更多