gpt4 book ai didi

python - 如何知道python中2个列表中相同索引的值是正数还是负数?

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:29 24 4
gpt4 key购买 nike

2个相同长度的列表,都是float或int类型,正负,不可能为零。我只想知道同一索引中的所有值是否具有相同的方向(正或负)。这是逻辑,还有更好的方法吗?

def same_direction(list1, list2):
diff = []
for i in len(list1):
if (list1[i] > 0 and list2[i] > 0) or (list1[i]< 0 and list2[i] < 0):
pass
else:
diff.append(i)
if diff:
return False
return True

same_direction([1, 2, 3], [3, 7, 9]) True
same_direction([-1, 2, 3], [1, 2, 3]) False

最佳答案

你可以 zip配对数字的列表,并检查每对数字是否具有相同的符号。用 all 包裹上面一旦找到 False 值,它就会终止:

def same_direction(l1, l2):
return all((x > 0) == (y > 0) for x, y in zip(l1, l2))

print(same_direction([1, 2, 3], [3, 7, 9]))
print(same_direction([-1, 2, 3], [1, 2, 3]))
print(same_direction([-1, 2, 3], [-1, 2, 3]))

输出:

True
False
True

或者,您可以将这些对相乘并检查结果是否大于 0:

def same_direction(l1, l2):
return all(x * y > 0 for x, y in zip(l1, l2))

关于python - 如何知道python中2个列表中相同索引的值是正数还是负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com