简体   繁体   中英

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.

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

TypeError: 'int' object is not subscriptable

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, 17, '']

I absolutely don't see why you need enumerate() here.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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