我试图比较python中三个列表的值,并根据这些比较创建一个新列表。为了使它更容易混淆,当statement = true时,第三个列表计数(+1)。
例如:
list1 = [5,10,15,20,25]
list2 = [3,6,9,12,15]
list3 = [0,1,11,21,28]
list4 = []
if list1 >= list3 and list2 <= list3:
list4 = 0
else:
list4 = list4 + 1
所以list4应该是这样的: list4 [1,2,0,1,2]
非常感谢任何帮助!
由于
答案 0 :(得分:3)
您可以使用generator function和zip
:
def solve(list1, list2, list3):
last = 0
for a, b, c in zip(list1, list2, list3):
if a >= c and b <= c:
yield 0
last = 0
else:
last += 1
yield last
...
>>> list(solve(list1, list2, list3))
[1, 2, 0, 1, 2]
答案 1 :(得分:0)
list1 = [5,10,15,20,25]
list2 = [3,6,9,12,15]
list3 = [0,1,11,21,28]
answer = []
app = 0
for a,b,c in zip(list1, list2, list3):
if a>=c>=b:
app = 0
else:
app += 1
answer.append(app)
证明:
>>> list1 = [5,10,15,20,25]
>>> list2 = [3,6,9,12,15]
>>> list3 = [0,1,11,21,28]
>>> answer = []
>>>
>>> app = 0
>>> for a,b,c in zip(list1, list2, list3):
... if a>=c>=b:
... app = 0
... else:
... app += 1
... answer.append(app)
...
>>> answer
[1, 2, 0, 1, 2]