I've been hammering my head for some time over this issue but can't seem find a solution for this, hence I ask for the assistance. PS: still a bit new to programming
I have lists in a list:
[(2012, 'january', 'monday'), (2012, 'february', 'monday'), (2012, 'january', 'tuesday')]
What I want is a new list with lists, when giving in the input "monday':
[(2012, 'january', 'monday'), (2012, 'february', 'monday')]
So far my code:
lists = [(2012, 'january', 'monday'), (2012, 'february', 'monday'), (2012, 'january', 'tuesday')]
day = input("Give day: ") #monday
def select_monday(lists, day):
list2 = []
for list in lists:
if list[2] == day: #from here I'm stuck and do not know how to continue
list2.append(list[2])
else:
return None
return list2
Result: None
I have no clue how to get all the lists with a certain value
Your code was fine, except, you don't need else
statement, because otherwise during next iteration you will loose the results from the previous steps; also you should actually call your function:
lists = [(2012, 'january', 'monday'), (2012, 'february', 'monday'), (2012, 'january', 'tuesday')]
day = input("Give day: ") #monday
def select_monday(lists, day):
list2 = []
for list in lists:
if list[2] == day: #from here I'm stuck and do not know how to continue
list2.append(list)
return list2
print(select_monday(lists, day))
And here's a more compact function:
def select_monday_2(lists, day):
return list(filter(lambda x: x[2] == day, lists))
print(select_monday_2(lists, day))
You return None
if the day is not Monday. This works better:
def select_monday(lists, day):
list2 = []
for lst in lists:
if lst[2] == day:
list2.append(lst)
return list2
Furthermore, append the whole list, not only the weekday. Finally, better not use list
as variable name because it is a built-in.
Now:
>>> select_monday(lists, day)
[(2012, 'january', 'monday'), (2012, 'february', 'monday')]
Shorter alternative, using a list comprehension:
>>> [x for x in lists if x[2] == day]
[(2012, 'january', 'monday'), (2012, 'february', 'monday')]
The problem with this is the else statement. If even one of the checks is false then it will return None
. Remove the else statement and get rid of the [2]
on the list in the append
statement, unless you just want to append the day.
lists = [(2012, 'january', 'monday'), (2012, 'february', 'monday'), (2012, 'january', 'tuesday')]
day = input("Give day: ") #monday
def select_monday(lists, day):
list2 = []
for list in lists:
if list[2] == day: #from here I'm stuck and do not know how to continue
list2.append(list)
return list2
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.