简体   繁体   English

Python - 过滤(lambda)元组索引错误列表

[英]Python - filter(lambda) list of tuples index error

I'm trying to filter a tuple as follows...some code not included for brevity: 我正在尝试按如下方式过滤元组...为简洁起见,不包括一些代码:

    1) print >> sys.stderr, "audio", audio
    2) print >> sys.stderr, "audio[0]", audio[0]
    3) print >> sys.stderr, "audio[1]", audio[1]
    4) audio_lang = filter(lambda a: a[1]==LANG, audio)

It is being passed a tuple with 2 elements, the run is as follows: 它传递了一个带有2个元素的元组,运行如下:

 D:\Staging\Test>cleanMKV.py .
 audio [('fre',), ('eng',)]
 audio[0] ('fre',)
 audio[1] ('eng',)
 Traceback (most recent call last):
 File "D:\Staging\Test\cleanMKV.py",
 audio_lang = filter(lambda a: a[1]
 File "D:\Staging\Test\cleanMKV.py",
 audio_lang = filter(lambda a: a[1]
 IndexError: tuple index out of range

The tuple was created properly with RE and I'm at a point I want to filter as shown on line 4. It is trying to reference the audio a[1] in audio. 使用RE正确创建了元组,我正处于我想要过滤的点,如第4行所示。它试图在音频中引用音频a [1]。

Any help appreciated. 任何帮助赞赏。

First, you define 首先,你定义

audio = [('fre',), ('eng',)]

which is actually a list of two elements ('fre',) and ('eng',) , which are both tuples containing only a single element, which are 'fre' and 'eng' respectively. 这实际上是两个元素('fre',)('eng',) ,它们都是仅包含单个元素的元组,分别是'fre''eng'

Now, if you do 现在,如果你这样做

audio_lang = filter(lambda a: a[1]==LANG, audio)

you are saying to keep only elements of audio, where the second elements equals to LANG . 你要说的只保留音频元素,其中第二个元素等于LANG But as your list elements ('fre',) and ('eng',) are tuples of length 1, you are getting 但是当你的列表元素('fre',)('eng',)是长度为1的元组时,你就得到了

IndexError: tuple index out of range

because you are trying to access the second elements, which do not exist. 因为您正在尝试访问不存在的第二个元素。

You could do 你可以做到

audio_lang = filter(lambda a: a[0]==LANG, audio)

that is access the first element or redefine audio and do 这是访问第一个元素或重新定义音频和做

audio = ['fre', 'eng']
audio_lang = filter(lambda a: a == LANG, audio)

But I do not understand, what are you trying to accomplish, so this might not be what you want. 但是我不明白,你想要完成什么,所以这可能不是你想要的。 But hopefully this explains the source of the error you are having. 但希望这可以解释您所遇到的错误的根源。

a is a tuple but audio is a list. a是一个元组,但audio是一个列表。 There is only one item in each of the two tuples that make up audio . 两个元组中的每一个中只有一个组成audio Therefore, evaluating either audio[0][1] or audio[1][1] will return tuple index out of range . 因此,评估audio[0][1]audio[1][1]将使tuple index out of range

>>> audio = [('fre',),('eng',)]

>>> audio
[('fre',), ('eng',)]
>>> audio[0]
('fre',)
>>> audio[0][0]
'fre'
>>> audio[0][1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

... but: ......但是:

>>> audio = [('fre',1),('eng',2)]
>>> audio[0][1]
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM