简体   繁体   English

使用枚举从 python 列表中获取值

[英]Get value from a python list using enumerate

I have this list我有这个清单

item = [
    [1, 2, 'W', 4, 5],
    [16, 17, 'W', 19, 20],
    [],
    [],
    [],
    ['1', '', 'D', '3120', '3456']
]

I need to get position 2 of each element where we have values.我需要获取我们有值的每个元素的位置 2。

I'm trying我正在努力

v_sal = [x for x, sal in enumerate(item) if sal]
x = [i for i in item if i]

for i in range(0,len(x)):
    for pos, val in enumerate(x[i]):
      v2=pos[2]

I need to assign position 2 of each array in a variable but I have this error我需要在变量中分配每个数组的位置 2,但我有这个错误

TypeError: 'int' object is not subscriptable TypeError:“int”对象不可下标

I assume this is your expected output for "position 2" in the meaning of the second position which would be index 1 for a list in Python:我假设这是您对“位置 2”的预期输出,即第二个位置的含义,这将是 Python list的索引1

[2, 17, '']

I absolutely don't see why you need enumerate() here.我绝对不明白为什么你需要enumerate()在这里。

Here is the solution for this.这是解决方案。

result = []

for element in item:
    try:
        result.append(element[1])
    except IndexError:
        pass

print(result)

You don't have to explicit check if there are values in the element or not.您不必显式检查元素中是否有值。 Just catch the exception.只需捕获异常。

You may utilize itertools library, or more-itertools , which is extremely useful when you work with an iterable object.您可以使用itertools库或more-itertools ,这在您使用可迭代对象时非常有用。

from itertools import islice

item = [
    [1, 2, 'W', 4, 5],
    [16, 17, 'W', 19, 20],
    [],
    [],
    [],
    ['1', '', 'D', '3120', '3456']
]

# https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/recipes.html#nth
def nth(iterable, n, default=None):
    """Returns the nth item or a default value.

    >>> l = range(10)
    >>> nth(l, 3)
    3
    >>> nth(l, 20, "zebra")
    'zebra'

    """
    return next(islice(iterable, n, None), default)


if __name__ == "__main__":
    f1 = [nth(l, 1) for l in item]
    f2 = [snds for l in item if (snds:=nth(l, 1)) is not None]  # Walrus operator is available > 3.8
    print(f1)
    # [2, 17, None, None, None, '']

    print(f2)
    # [2, 17, '']

See, https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/recipes.html#nth见, https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/recipes.html#nth

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

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