Skip to main content
 首页 » 编程设计

python之使用具有两个 for 循环的列表理解从两个列表中选择元素

2025年05月04日9me-sa

我有以下作业问题:

制作一个使用 I 和 R 的元素的列表推导式,并仅选择 I 和 R 的非负整数元素。 注意:为此您应该使用两个 for 循环。

列表

I = [-1, 0, 1, 2] 
R = [2.7818, 0.0, -3.14159] 

期望的输出

[0, 1, 2] 

谢谢,

考特尼

附言。我能想到的解决问题的唯一方法是将两个列表合二为一:

NonNeg = [i for i in I+R if(i >= 0 and isinstance(i,int))]

请您参考如下方法:

我找到了这个问题的另一个解决方案。这个答案不能一概而论,但符合教授给我们设定的学习目标:如何在列表推导中使用嵌套的for循环。

Since there is only 1 value in list R that is greater than 0, the result of the list comprehension's first iteration is the only result returned

numbers = [(i,r) for i in I for r in R if(r>0)] 
result: [(-1, 2.7818), (0, 2.7818), (1, 2.7818), (2, 2.7818)] 

For each tuple in the list i, for each element j in the tuple return elements that are greater than zero and an integer

NonNeg = [j for i in numbers for j in i if(j >= 0 and j%1==0)] 
result:[0, 1, 2] 

A more generalizable is solution would be what I originally posted:
NonNeg2 = [i for i in I+R if(i >= 0 and isinstance(i,int))]
result:[0, 1, 2]