Ted Idzikowski - 1 year ago 60
Python Question

# Checking for lists inside 2D with value in specific index & sorting by index of the list without key = lambda or itemgetter

I have two questions:

First Question

How do you check for lists inside a 2D list that have in a specific index, a specific value. But the complexity is that the specific index is a string in which the specific value is looked for.

For example, if:

``````>>> question = [['Hello', 'Bob', '4/11/1976'], ['No wonder', 'Harry', '11/27/2011'], ['Just listen', 'Schreibert', '7/8/1984'], ['Wanna live', 'Andrew', '4/25/1976']]
``````

So, let's say the user inputs as follows:

``````>>> Enter month: 4
>>> Enter year: 1976
``````

How can question become:

``````>>> question
>>> [['Hello', 'Bob', '4/11/1976'],['Wanna live', 'Andrew', '4/7/1976']]
``````

Second Question

For the same case, I would like to know if there's a way to sort the 2D-list question according to the day e.g. (4/11/year).

Note: There's questions that have already an answer for this, BUT none answer without using key = lambda or importing itemgetter. So I would like to know if there's such way without.

The expected outcome for this question would then be:

``````>>> question
>>> [['Wanna live', 'Andrew', '4/7/1976'],['Hello', 'Bob', '4/11/1976']]
``````

I attempted only for questions one, because I have no clue about how to do it for two:

``````>>>month = input('Enter month: ')
>>>year = input('Enter year: ')
>>>ans2 = [d for d in questions1 if (int(d[2][-10:-8]) == int(month)) and (int(d[2][-4:]) == int(year))]
``````

``````def matches(entry):
date = entry[2]
return date.startswith('%s/' % month) and date.endswith('/%s' % year)

question = list(filter(matches, question))
``````

I chose to use a function because I think it makes the code cleaner in this case, but if you don't want to:

``````question = [entry for entry in question if
entry[2].startswith('%s/' % month) and
entry[2].endswith('/%s' % year)]
``````

For the second question, I'm ignoring your request to not use `key` because it's simply a bad idea, so here it is:

``````question.sort(key=lambda e: int(e[2].split('/')[1]))
``````

But if you really wanted to not use `key`, the general technique is outlined here: https://wiki.python.org/moin/HowTo/Sorting#The_Old_Way_Using_Decorate-Sort-Undecorate

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download