将普通的 for 循环结构转换为列表理解结构
Translate a normal for loop structure into list comprehension structure
我试着翻译了以下结构:
newDV = []
for row in dataVector:
for cell in row:
newDV.append((cell if row.index(cell) != 0 else 'other'))
在以下列表理解结构中:
[
cell
for cell in row
for row in dataVector
if row.index(cell) != 0 else 'other'
]
但不幸的是我收到以下错误:
UnboundLocalError: local variable 'row' referenced before assignment
我不明白我哪里错了。
有什么建议吗?
提前致谢
试试这个:
[
cell
for row in dataVector
for cell in row
if row.index(cell) != 0 else 'other'
]
这应该适合你,它使用 python 三元运算符 (, )[test]
[
('other', cell)[row.index(cell)!=0]
for row in dataVector
for cell in row
]
我试着翻译了以下结构:
newDV = []
for row in dataVector:
for cell in row:
newDV.append((cell if row.index(cell) != 0 else 'other'))
在以下列表理解结构中:
[
cell
for cell in row
for row in dataVector
if row.index(cell) != 0 else 'other'
]
但不幸的是我收到以下错误:
UnboundLocalError: local variable 'row' referenced before assignment
我不明白我哪里错了。
有什么建议吗?
提前致谢
试试这个:
[
cell
for row in dataVector
for cell in row
if row.index(cell) != 0 else 'other'
]
这应该适合你,它使用 python 三元运算符 (
[
('other', cell)[row.index(cell)!=0]
for row in dataVector
for cell in row
]