将多个值与Python中的列表分配时,如何使用循环?
我正在尝试将值与两个列表划分,我想用商输出一个列表。我遇到的问题是,所有价值都在彼此之间经历并分裂。
如果我有两个这样的列表:
lst1 = [101, 2, 3]
lst2 = [69, 0, 0]
当我将LST2 [0]/LST1 [0],LST2 [1]/LST1 [1],LST2 [2]/LST1/LST1 [2]分配时,我希望输出看起来像这样
output_lst = [0.6831683168316832, 0.0, 0.0]
。代码看起来像这样,它为我提供了这样的输出:
output_lst = [((x)/(y)) for x in lst2 for y in lst1]
print(output_lst)
#[0.6831683168316832, 34.5, 23.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
我也尝试了此功能,这也使我提供了相同的输出:
for x in lst2:
for x in lst1:
output_lst = x/y
print(output_lst)
#[0.6831683168316832, 34.5, 23.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
我试图避免单独进行每个计算,然后将其全部放入列表中。我该如何将值按顺序划分,而没有反复划分的值?
我的代码在哪里出错?感谢任何帮助 - 谢谢。
I am trying to divide values from two lists by each other, and I want to output a list with the quotients. The problem I am having is that all of the values are going through each other and dividing.
If I have two lists like this:
lst1 = [101, 2, 3]
lst2 = [69, 0, 0]
I want the output to look like this when I divide lst2[0]/lst1[0], lst2[1]/lst1[1], lst2[2]/lst1[2]:
output_lst = [0.6831683168316832, 0.0, 0.0]
My code looks like this, which gives me an output like this instead:
output_lst = [((x)/(y)) for x in lst2 for y in lst1]
print(output_lst)
#[0.6831683168316832, 34.5, 23.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
I've also tried this, which also gives me the same output:
for x in lst2:
for x in lst1:
output_lst = x/y
print(output_lst)
#[0.6831683168316832, 34.5, 23.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
I'm trying to avoid doing each calculation individually and then putting it all into a list. How can I just divide the values in order, with no values being repeatedly divided?
Where am I going wrong in my code? Would appreciate any help - thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是
zip
函数的工作。使用相同的元素顺序...output_lst = [x/y for x,y in zip(lst2,lst1)]
This is a job for the
zip
function. Using the same order of elements...output_lst = [x/y for x,y in zip(lst2, lst1)]
您的第一个代码示例真的很接近。只需将
zip
添加到混音中,就在那里。You are really close with your first code sample. Just add
zip
into the mix and you are there.