这种方式有没有更短的路?

问题描述 投票:-1回答:3

假设我有变量a,b,c,d,e,f ..每当6个变量中的2个随机变为值= 0时。所以我的代码是这样的

if(a == 0 and b == 0):
   run c,d,e,f
elif(a == 0 and c == 0):
   run b,d,e,f
...
...
continue until end of all combination

所以编码会很长,还有其他方法吗?

python
3个回答
3
投票

您可以将所有数字放入列表中,然后将该列表的列表组件提供给run函数 - 忽略0的元素:

def run(p1,p2,p3,p4):
    print(p1,p2,p3,p4)

# 3 test cases
for d in [ [ 1,2,0,3,4,0], [0,0,2,3,4,1], [4,3,0,2,1,0]]:
    run(*[x for x in d if x])  #  *[1,2,3] makes python provide the elements as params

输出:

1 2 3 4
2 3 4 1
4 3 2 1
  • run( *[1,2,3])run(1,2,3)相同
  • 0是Falsy - 所以*[x for x in d if x]对于d=[0,1,2,3,0]只使用x中的d的非虚假值:*[1,2,3]

  • truth value testing
  • 你可以将run(*[x for x in d if x])列表与生成器comp交换,如果你喜欢run(*(x for x in d if x))以避免列表创建(这不重要;))

@Mehrdad Dowlatabadi提出了一个有趣的问题 - 如果任何其他的参数为0,则由于函数参数与列表推导中提供的参数不匹配而导致错误 - 您可以通过定义默认值来否定:

def run(p1=0, p2=0, p3=0, p4=0):
    print(p1,p2,p3,p4)

因此,如果您将[0,1,2,0,0,0]加入其中,它仍然会运行。


2
投票

如果要运行具有未设置为0的变量的函数,可以先创建不为0的元素列表

elements = [element for element in a, b, c, d, e if element !=0]

然后使用元素列表作为参数调用该函数

run(*elements)

作为一个班轮:

run(*[element for element in a, b, c, d, e if element !=0])

0
投票

让运行列表:

def run(lst):
    ...

然后使用过滤功能:

run(filter(None, [a, b, c, d, e, f]))

qazxsw poi删除所有的虚假元素。

© www.soinside.com 2019 - 2024. All rights reserved.