我正在尝试比较Python中三个列表的值,并根据这些比较创建一个新列表。为了使其更令人困惑,当语句= 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]
任何帮助将不胜感激!
谢谢
您可以使用Generator函数和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]
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]