将多个值与Python中的列表分配时,如何使用循环?

发布于 2025-02-14 00:27:55 字数 768 浏览 4 评论 0原文

我正在尝试将值与两个列表划分,我想用商输出一个列表。我遇到的问题是,所有价值都在彼此之间经历并分裂。

如果我有两个这样的列表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心头的小情儿 2025-02-21 00:27:55

这是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)]

素衣风尘叹 2025-02-21 00:27:55

您的第一个代码示例真的很接近。只需将zip添加到混音中,就在那里。

lst1 = [101, 2, 3]
lst2 = [69, 0 ,0]

output = [x/y for x, y in zip(lst2, lst1) if y != 0]
print(f"{output}")

You are really close with your first code sample. Just add zip into the mix and you are there.

lst1 = [101, 2, 3]
lst2 = [69, 0 ,0]

output = [x/y for x, y in zip(lst2, lst1) if y != 0]
print(f"{output}")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文