4

I have a list of lists, each with four items. For each list within it, I want to take indexes 0 and 2, put them in a list, then put all those lists in one list of lists. So, using for loops, I got what I wanted by doing this:

finallist = []
for i in range(len(weather_data)):
    templist = []
    templist.append(weather_data[i][0])
    templist.append(weather_data[i][2])
    finallist.append(templist)

so that gets me a list like [['2018-02-01', -18.6], ['2018-02-02', -19.6], ['2018-02-03', -22.3]]. But for this assignment, I'm supposed to do that by using one list comprehension. Best I can get is this:

 weekendtemps = [x[0] for x in weather_data if (x[1] == "Saturday" or x[1] == "Sunday")]

But that only gives me [['2018-02-01'], ['2018-02-2'], ['2018-02-03']]. How do I get both weather_data[0] and weather_data[2] using list comprehension?

2
  • You can have an empty list literal like the ones you’re using, [], but you can also have list literals with items inside. [1, 2, 3] Commented Feb 7, 2019 at 4:57
  • Just add x[2] to what you tried in your one list comprehension Commented Feb 7, 2019 at 4:59

1 Answer 1

2

Why not:

weekendtemps = [[x[0],x[2]] for x in weather_data if (x[1] == "Saturday" or x[1] == "Sunday")]

Or more efficient:

weekendtemps = [[x[0],x[2]] for x in weather_data if x[1] in ['Saturday', 'Sunday']]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.