python - 在列表python 3中查找子列表的索引

标签 python python-3.5

我有一个列表,最初是空的,但用户将子列表附加到列表中。

然后,我需要使用子列表的前 2 个元素来搜索特定子列表的索引。如果前两个元素是仅有的两个元素,则此方法有效,但当用户将更多详细信息附加到子列表中时则无效。

我需要一种仅使用前两个元素来搜索子列表索引的方法。有任何想法吗?

database=[] 
fn=input("Enter the students first name:")
sn=input("Please enter the students surname:")

rr=(any(fn and sn in i for i in database))        

if rr==True:
 print("true")
 pos=(database.index([fn, sn]))

最佳答案

您需要找到特定的子列表以将其提供给index函数,例如通过修改检查器以返回子列表

for sublist in database:
  if fn in sublist and sn in sublist:
    index_sublist = sublist
    break

然后通过找到的子列表搜索索引

pos = (database.index(index_sublist))

顺便检查一下

fn and sn in i for i in database

在这种情况下,您检查 fn 是否存在并且 sn 是否在 i 中。尝试一下

fn in i and sn in i for i in database

此外,还有更省时的方法来存储任务值,例如在以 tuple(sublist[:2]) 作为键和子列表作为值的字典中

关于python - 在列表python 3中查找子列表的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197516/

相关文章:

python Pandas : Getting the Index of All Rows that Match a Column Value

python - Optional[Type[Foo]] 在 Python 3.5.2 中引发 TypeError

python - 是否可以使用并发.futures 在事件发生后执行 tkinter 类内的函数/方法?如果是,怎么办?

python - 为什么 __getitem__ 在 Python 3.5 中被调用而在 Python 2.7 中不被调用?

opencv - 大多数 cv2 元组参数在 python 3.5 (windows 7) 中不起作用

python - pandas:将列和行信息 reshape 为单独的列

python - Django WSGIRequest.get_full_path() 不返回完整的 URI

python - 如何从 Python Twisted 中进行 SSH 端口转发?

ubuntu - Pycharm - 未找到 Python 打包工具

python 多处理: processes don't work