2

Alright, so I have a list of 296 data points and four blank spaces. I cannot edit this list of data points. i have another list of 300 data points. I want to multiply the lists together, with python skipping multiplying the data points when a blank space shows up. Here's what the lists look like:

a = [[6], [7], [], [7]]
b = [[100], [200], [300], [400]]

What sort of exception handling would I have to put in? My current code uses

for items in mathList:
 try:
 sumlist = [x * y for x,y in zip(grearp, rex)]
 except:
 print 'No data for',items
asked Jul 26, 2011 at 14:35

2 Answers 2

5

Is the length of both lists actually 300 then, with 0's or blank strings for the missing data points? If so, this should come close:

newList = [x[0] * y[0] if x else None for x, y in zip(l1, l2)]

-- Edited --

I realized I didn't review the sample data quite as well as I could've. As the inner list is empty it'll fail a truth test on its own, so just if x. Also, added indexing for the inner lists on x, y.

answered Jul 26, 2011 at 14:38
Sign up to request clarification or add additional context in comments.

4 Comments

This won't work as he has lists of lists, not lists of integers.
It's okay, I just removed the minilists and this worked. Thanks for your help!
@miles82 -> you're correct. I've modified the code slightly. In point of fact though, sometimes it's about demonstrating an approach more than it is providing a copy/paste solution. The question boils down to "how do I conditionally operate within a list comprehensions" which both versions of my code demonstrate.
@Tim - Happy to help! I'm glad it made sense. :)
0

Think that you can also use something like this(code below will prepare lists to be the same size and then calculates '*' if both values present - otherwise include the only value exist):

from itertools import izip_longest
a = [[6], [7], [], [7]]
b = [[100], [200], [300], [400]]
newList = [[x[0] * y[0]] if x and y else (x or y) for x,y in izip_longest(a,b, fillvalue=[])]
answered Jul 26, 2011 at 14:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.