Python 具有双重条件的函数
Python function with double condition
我想创建一个函数,returns 奇数位置的列表元素或列表的负元素。
我的解决方案适用于第一个断言,但第二个会生成 AssertionError,因为 returns [-1, -2, 1] 而不是 [-1, -2]。有什么建议吗?
def solution(input):
output = []
for item in input:
if item < 0:
output.append(item)
elif not item % 2 == 0:
output.append(item)
return output
assert solution([0,1,2,3,4,5]) == [1,3,5]
assert solution([1,-1,2,-2]) == [-1,-2]
您想要奇数位置的数字,但您的 %
检查检查的是列表中的实际值,而不是它们的位置。
在遍历列表时尝试使用 enumerate
获取索引和值:
def solution(input):
output = []
for ix, item in enumerate(input):
if item < 0 or ix % 2 != 0:
output.append(item)
return output
另外,为了完整起见,您可能需要考虑将此添加到您现有的代码中:
if any(i < 0 for i in output):
return [i for i in output if i < 0]
,因为它测试是否存在负数,return 仅测试存在的负数。然而,从我的角度来看,HumphreyTriscuit 的回答是更好的解决方案。
一行定义求解函数:
def solution(input):
return [input[pos] for pos in range(len(input)) if not pos %2 == 0 or input[pos] < 0]
print solution([0,1,2,3,4,5,7])
print solution([1,-1,2,-2, -3])
我想创建一个函数,returns 奇数位置的列表元素或列表的负元素。
我的解决方案适用于第一个断言,但第二个会生成 AssertionError,因为 returns [-1, -2, 1] 而不是 [-1, -2]。有什么建议吗?
def solution(input):
output = []
for item in input:
if item < 0:
output.append(item)
elif not item % 2 == 0:
output.append(item)
return output
assert solution([0,1,2,3,4,5]) == [1,3,5]
assert solution([1,-1,2,-2]) == [-1,-2]
您想要奇数位置的数字,但您的 %
检查检查的是列表中的实际值,而不是它们的位置。
在遍历列表时尝试使用 enumerate
获取索引和值:
def solution(input):
output = []
for ix, item in enumerate(input):
if item < 0 or ix % 2 != 0:
output.append(item)
return output
另外,为了完整起见,您可能需要考虑将此添加到您现有的代码中:
if any(i < 0 for i in output):
return [i for i in output if i < 0]
,因为它测试是否存在负数,return 仅测试存在的负数。然而,从我的角度来看,HumphreyTriscuit 的回答是更好的解决方案。
一行定义求解函数:
def solution(input):
return [input[pos] for pos in range(len(input)) if not pos %2 == 0 or input[pos] < 0]
print solution([0,1,2,3,4,5,7])
print solution([1,-1,2,-2, -3])