繁体   English   中英

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

[英]Get value from a python list using enumerate

我有这个清单

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

我需要获取我们有值的每个元素的位置 2。

我正在努力

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]

我需要在变量中分配每个数组的位置 2,但我有这个错误

TypeError:“int”对象不可下标

我假设这是您对“位置 2”的预期输出,即第二个位置的含义,这将是 Python list的索引1

[2, 17, '']

我绝对不明白为什么你需要enumerate()在这里。

这是解决方案。

result = []

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

print(result)

您不必显式检查元素中是否有值。 只需捕获异常。

您可以使用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, '']

见, 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