python - Find index element in a list of lists and strings
问题描述
I have a list containing strings and lists. Something like:
l = ['a', 'b', ['c', 'd'], 'e']
I need to find the index of an element I'm looking for in this nested list. For instance, if I need to find c
, the function should return 2
, and if I'm looking for d
, it should return 2
too. Consider that I have to do this for a large number of elements. Before I was simply using
idx = list.index(element)
but this does not work anymore, because of the nested lists. I cannot simply flatten the list, as I then shall use the index in another list with the same shape as this one.
Any suggestion?
解决方案
这是一种方法,迭代列表。
前任:
l = ['a', 'b', ['c', 'd'], 'e']
toFind = "c"
toFind1 = "d"
for i, v in enumerate(l):
if isinstance(v, list):
if toFind1 in v:
print(i)
else:
if toFind1 == v:
print(i)
推荐阅读
- c++ - Msys2 不为 GTK3 安装 lib 文件
- javascript - UTF-8 vs UTF-16 和 UTF-32 转换混淆
- python - 如何在同一个 Pandas 数据框单元格中的列表元素之间放置换行符?
- python - 为什么“num[0]+=1 if X else num[1]+=1”语法无效?
- linux - Linux:sed:-e 表达式#1,字符 1:未知命令:`.'
- javascript - 为什么在 JavaScript 中分配 Infinity 不会引发错误,但不起作用?
- javascript - Ajax 调用 Python 脚本。我错过了什么?
- pdf - 通过 SendGrid 发送受密码保护的附件
- r - shinyapps.io “与服务器断开连接”/“内存不足”问题
- c# - Microsoft.NET.Sdk.Functions 和 xunit.runner.visualstudio 不兼容