简体   繁体   中英

Convoluted Conditional List comprehension

Let's say I have a set of tuples, each consist of 4 integers (A, B, C, D)

And I have a input tuple (x, y, z, w) of 4 integer

I wanted to make a list of all element in the set where

(abs(A - x) + abs(B - y) + abs(C - z) + abs(D - w)) / 4 <= i

Where i is a user-defined threshold.

I'm trying a method obtained by another guy from another question, that is to do a List comprehension, I tried the following:

SET = my set of 4-tuples
input = the input tuple

for w in [element for element in SET
                              if ((sum(abs(x - y)) for x, y in zip(element, input)) / 4) <= i]:

      Do something here

but I keep getting error messages like:

if ((sum(abs(x - y)) for x, y in zip(key, js)) / 4) == 0]:
TypeError: unsupported operand type(s) for /: 'generator' and 'int'

I have no idea how to solve that problem, I looked up the definition of a generator it said a generator is just a function that behaves like a iterator, I assume it is my sum(abs(x - y)) , but this thing should return a number, I'm so confused, please help me out, thank you very much!!!

The issue is you are trying to divide a generator by an int .

for w in [element for element in SET
    if ((sum(abs(x - y)) for x, y in zip(element, input)) / 4) <= i]:
        ^---------------- right here -------------------^ 

is your generator.

You need the sum to run over the whole of the generator, and divide that result by 4.

    if (sum((abs(x - y)) for x, y in zip(element, input)) / 4) <= i]:

Note that sum is out one paren. Of course, that doesn't work, since zip(element, input) isn't valid ( element isn't iterable). I'm not sure what it's supposed to be. If it's element matched with each value of input , use (element, )*4 .

Edit: I just reread your question, if I understand, SET is something like {(1,2,3,4), (5,6,7,8)} , at which point it is iterable, and should work if you fix the generator issue.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM