Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - Getting <generator object <genexpr>

I have 2 lists:

first_lst = [('-2.50', 0.49, 0.52), ('-2.00', 0.52, 0.50)]
second_lst = [('-2.50', '1.91', '2.03'), ('-2.00', '1.83', '2.08')]

I want to do the following math to it:

Multiply 0.49 by 1.91 (the corresponding values from first_lst and second_lst), and multiply 0.52 by 2.03 (corresponding values also). I want to do that under condition that values at position 0 in each corresponding tuple is idential so -2.50 == -2.50 etc. Obviously, we do the same math for remaning tuples as well.

My code:

[((fir[0], float(fir[1])*float(sec[1]), float(fir[2])*float(sec[2])) for fir in first_lst) for sec in second_lst if fir[0] == sec[0]]

Generates however some object:

[<generator object <genexpr> at 0x0223E2B0>]

Can you help me fix the code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use tuple() or list() to convert that generator expression to a list or tuple:

[tuple((fir[0], fir[1]*sec[1], fir[2]*sec[2]) for fir in first_lst)
                               for sec in second_lst if fir[0] == sec[0]]

Working version of your code:

>>> first_lst = [tuple(float(y) for y in x) for x in first_lst]
>>> second_lst = [tuple(float(y) for y in x) for x in second_lst]

>>> [((fir[0],) + tuple(x*y for x, y in zip(fir[1:], sec[1:]))) 
                  for fir in first_lst for sec in second_lst if fir[0]==sec[0]]
[(-2.5, 0.9359, 1.0555999999999999), (-2.0, 0.9516000000000001, 1.04)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...