Python:count直到列表中的元素是一个元组

Mat*_*NNZ 3 python tuples list python-2.7

我有一个这样的列表:

MyList = [2,3,(1,2),5]
Run Code Online (Sandbox Code Playgroud)

其中元素0,1和3是整数,而元素2是元组.我想创建一个计数器,告诉我在元组出现之前列表中有多少元素.在这个例子中,我想要一个计数器,它将取值2(2个元素,2和3,在第一个元组之前).我尝试过以下方法:

counter = 0
while MyList[counter] is not tuple: 
    counter = counter + 1
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为当它评估语句"(1,2)不是元组"而不是提高False时它继续取值True.知道问题可能是什么以及如何解决问题?谢谢.

Mar*_*ers 10

你可以使用for循环和break输出:

counter = 0
for elem in MyList:
    if isinstance(elem, tuple):
        break
    counter += 1
Run Code Online (Sandbox Code Playgroud)

或者,使用enumerate():

for counter, elem in enumerate(MyList):
    if isinstance(elem, tuple):
        break

# counter *could* be unbound if `MyList` is empty
Run Code Online (Sandbox Code Playgroud)

或者您可以使用itertools.takewhile():

from itertools import takewhile

counter = sum(1 for elem in takewhile(lambda e: not isinstance(e, tuple), MyList))
Run Code Online (Sandbox Code Playgroud)

演示后一种方法:

>>> from itertools import takewhile
>>> MyList = [2,3,(1,2),5]
>>> sum(1 for elem in takewhile(lambda e: not isinstance(e, tuple), MyList))
2
Run Code Online (Sandbox Code Playgroud)


Tim*_*ker 8

使用isinstance()来确定对象的类型:

>>> counter = 0
>>> while not isinstance(MyList[counter], tuple):
...     counter += 1
...
>>> counter
2
Run Code Online (Sandbox Code Playgroud)


Abh*_*jit 6

只需使用发电机.它是最简单的.

next(index for index, elem in enumerate(MyList) if isinstance(elem, tuple))
Run Code Online (Sandbox Code Playgroud)