2024-04-23 23:14:22 发布
网友
我有以下作业问题:
做一个列表理解,使用I和R的元素,只选择I和R的非负整数元素。注意:为此,应使用两个For循环。
列表
I = [-1, 0, 1, 2] R = [2.7818, 0.0, -3.14159]
所需输出
[0, 1, 2]
谢谢你
考特尼
另外,我唯一能想到的回答问题的方法就是把这两个列表合并成一个这样:
NonNeg=[i+R中的i表示i,如果(i>;=0和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]
NonNeg2 = [i for i in I+R if(i >= 0 and isinstance(i,int))]
list1 = [1, 2, 3] list2 = [2.0, 4, 10.5] d = [x for x in list1+list2 if isinstance(x,int)] print(d)
说明:
使用+运算符组合列表
+
我找到了另一个解决办法问题。问题答案不可归纳,但符合教授为我们设定的学习目标:如何在列表理解中使用嵌套for循环。
说明:
使用
+
运算符组合列表相关问题 更多 >
编程相关推荐