简体   繁体   English

如何创建多个条件的排列(没有长 if 条件)

[英]How to create permutations of multiple conditions (without long if condition)

I have several variables that I need to permute with each other.我有几个变量需要相互置换。

Simple example with four variables: UP , DOWN , LEFT , RIGHT :带有四个变量的简单示例: UPDOWNLEFTRIGHT

#when variable UP is max
if UP > RIGHT > LEFT > DOWN or UP > RIGHT > DOWN > LEFT or UP > LEFT > RIGHT >DOWN or UP > LEFT > DOWN > RIGHT or UP > DOWN > RIGHT > LEFT or UP > DOWN > LEFT > RIGHT:
     some action ...

#when variable RIGHT is max
if RIGHT > UP > LEFT > DOWN or RIGHT > UP > DOWN > LEFT or RIGHT > LEFT > UP > DOWN or RIGHT > LEFT > DOWN > UP or RIGHT > DOWN > UP > LEFT or RIGHT > DOWN > LEFT > UP:
     some action ...

.
.
.

Is there any way to create permutations without so long if condition?有没有办法在没有这么长的条件下创建排列?

I think you'd be better off finding which one is highest, and then making one or more decisions off of that:我认为你最好找出哪个最高,然后据此做出一个或多个决定:

maxIndex = 0
values = [UP, DOWN, RIGHT, LEFT]
for curIndex in range(len(values))
    if values[curIndex] > values[maxIndex]:
        maxIndex = curIndex

if maxIndex == 0: #Up is highest
    ...
else if maxIndex == 1: #down is highest
    ...
else if...

There are always alternative approaches.总是有替代方法。 The if/elseif/elsif chain could be replaced with a dictionary full of lamdas, or several other constructs . if/elseif/elsif 链可以替换为充满 lamdas 的字典或其他几个结构 There's probably a math library out there that has a "find the highest value and return its index" function out there.那里可能有一个数学库,它有一个“找到最高值并返回它的索引”function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM