gython
gython

Reputation: 875

How to filter a nested list for an entry at an specific index?

I have a nested list, every sublist contains three entiries.

The second entry of the list (at index [1]) is a date. If there is no date than there is an entry 'No-Date'.

Now I want to filter the sublists based on this date. Every entry that is not from 2019 and 2018 should be filtered. Furthermore I also want the entries that have no date.

However with my code I only get the entries that have no date.

Sample of the list:

lim = [
        ['xxx', 'No-Date', 'xxx'],
        ['xxx', '2019-12-08', 'xxx'],
        ['xxx', '2019-07-12', 'xxx'],
        ['xxx', '2018-11-13', 'xxx'],
        ['xxx', '2017-10-03', 'xxx'],
        ['xxx', '2016-01-05', 'xxx'],
        ['xxx', '2019-10-24T15:09:00+02:00', 'xxx'],
       ]

The code as loop:

li_zj = []
filter1 = ['2019-', '2018-', 'No-Date']
for line in lim:
    for x in line:
        for f in filter1:
            if x in f:
                li_zj.append(line)
print(li_zj)

The code as list comprehension:

filter1 = ['2019-', '2018-', 'No-Date']
li_zj = [x for x in lim if any(f in x for f in filter1)]
print(li_zj)

Desired output:

li_zj = [
         ['xxx', 'No-Date', 'xxx'],
         ['xxx', '2019-12-08', 'xxx'],
         ['xxx', '2019-07-12', 'xxx'],
         ['xxx', '2018-11-13', 'xxx'],
         ['xxx', '2019-10-24T15:09:00+02:00', 'xxx'],
        ]

How can I do this correctly?

Upvotes: 0

Views: 93

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With str.startswith and simple list comprehension:

date_filter = ('2019-', '2018-', 'No-Date')
res = [x for x in lim if x[1].startswith(date_filter)]
print(res)

The output:

[['xxx', 'No-Date', 'xxx'],
 ['xxx', '2019-12-08', 'xxx'],
 ['xxx', '2019-07-12', 'xxx'],
 ['xxx', '2018-11-13', 'xxx'],
 ['xxx', '2019-10-24T15:09:00+02:00', 'xxx']]

Upvotes: 1

Related Questions