簡體   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