如何在Python3中获得列表中的列表编号?

2024-03-29 15:55:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取包含特定编号的嵌套列表的编号。这是我的密码:

listo = [[1,2],[3,4,5]]
for x in listo:
    if 3 in x:
       print(len(x))

我想得到的是嵌套列表中有3个的数字。我的代码返回3是因为我是函数len的一员,它只返回嵌套列表中的项数。输出应为:

2

因为数字3位于第二个嵌套列表中。计数从1开始,而不是从0开始。你知道吗

如何获得正确的输出?你知道吗


Tags: 函数代码in密码列表forlenif
3条回答

使用enumerate获取数组中元素的索引。你知道吗

l1 = ["eat","sleep","repeat"]

# printing the tuples in object directly
for ele in enumerate(l1):
    print ele

Output:
(0, 'eat')
(1, 'sleep')
(2, 'repeat')

上述代码也可以使用同样的方法。你知道吗

listo = [[1,2,3],[4,5]]
for ind,x in enumerate(listo):
     if 3 in x:
        print(ind)

使用enumerate

listo = [[1,2], [3,4,5]]

res = next(i for i, sublist in enumerate(listo) if 3 in sublist)
print(res)  # -> 1

请注意,Python是0索引语言;列表中的第一个元素的索引号为0。这就是为什么上面的代码返回1。如果您想获得2,那么,只需在其中添加1,或者更好地使用enumerate(enumerate(listo, 1))的可选start参数。你知道吗

要使上述防错1,可以指定在3不在任何子列表中时要返回的默认值。你知道吗

res = next((i for i, sublist in enumerate(listo) if 3 in sublist), 'N\A')

1next引发StopIteration如果它在没有找到返回对象的情况下耗尽iterable,除非提供了默认值。你知道吗

使用^{}将起始值指定为1

listo = [[1,2],[3,4,5]]
for i, x in enumerate(listo, 1):
    if 3 in x:
        print(i)

# 2

相关问题 更多 >