python - 列表处理。索引行和列
问题描述
我正在努力对列表数据结构中包含的行和列进行索引。目标是返回 '.' 的坐标。以包含在新列表中的元组的形式。
代码在下面给出为 3x3。答案应该是 [(0,0)]。
lst = [['.', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']]
我写的代码是:
def coor(lst):
new_lst = []
for row in lst:
for col in row:
if col == '.':
r = lst.index(row)
c = lst.index(col)
new_lst.append((r,c))
return new_lst
但是,代码是错误的。我想通过调用第一个列表的行索引,它应该返回 0,调用 col 的索引也返回 0。
解决方案
enumerate
将在这里为您提供帮助:
def coor(lst):
new_lst = []
for row_index, row in enumerate(lst):
for col_index, col in enumerate(row):
if col == '.':
new_lst.append((row_index, col_index))
return new_lst
结果coor(lst)
是[(0, 0)]
。
至于为什么您的原始代码首先不起作用,您需要更改c = lst.index(col)
为c = row.index(col)
,因为每个col
都包含在row
.
推荐阅读
- java - 计算整数真数的最佳性能实现?
- javascript - jQuery .toggle() 按钮需要被点击两次
- python - 自定义插值/最小化函数(又名曲线拟合)任何库
- javascript - 在这种情况下,我可以在兄弟组件之间共享数据吗?
- python - django rest 框架序列化程序中的关系数据库
- javascript - 深度学习——检测电线杆的特征
- javascript - 如何使用 JavaScript 定期打开 URL?
- android - 没有为“流”类型定义吸气剂“数据”
' - java - 在没有注释的情况下将 json 反序列化为 Jackson 中的引用字符串
- swift - Swift:变异转换参数(错误:不能在类型“MyObjectType”的不可变值上使用变异成员(又名“字典”)
')