[英]Convoluted Conditional List comprehension
Let's say I have a set of tuples, each consist of 4 integers (A, B, C, D)假设我有一组元组,每个元组由 4 个整数组成(A、B、C、D)
And I have a input tuple (x, y, z, w) of 4 integer我有一个输入元组 (x, y, z, w) 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 是用户定义的阈值。
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!!!我不知道如何解决这个问题,我查看了生成器的定义,它说生成器只是一个 function ,它的行为就像一个迭代器,我认为它是我的sum(abs(x - y)) ,但是这个东西应该返回一个数字,我很困惑,请帮助我,非常感谢!
The issue is you are trying to divide a generator
by an int
.问题是您试图将
generator
除以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.您需要
sum
来运行整个生成器,然后将该结果除以 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).当然,这不起作用,因为
zip(element, input)
无效( element
不可迭代)。 I'm not sure what it's supposed to be.我不确定它应该是什么。 If it's
element
matched with each value of input
, use (element, )*4
.如果它的
element
与input
的每个值匹配,请使用(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.编辑:我只是重读了你的问题,如果我理解的话,
SET
类似于{(1,2,3,4), (5,6,7,8)}
,此时它是可迭代的,如果你应该可以工作修复生成器问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.