如何针对单个值测试多个变量的相等性?

wa7juj8i  于 2022-09-18  发布在  Java
关注(0)|答案(30)|浏览(167)

我正在尝试编写一个函数,将多个变量与一个整数进行比较,并输出一个由三个字母组成的字符串。我想知道有没有办法把它翻译成Python。所以说:

x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0:
    mylist.append("c")
if x or y or z == 1:
    mylist.append("d")
if x or y or z == 2:
    mylist.append("e")
if x or y or z == 3: 
    mylist.append("f")

它将返回一个列表,其中包括:

["c", "d", "f"]
sf6xfgos

sf6xfgos1#

The most pythonic way of representing your pseudo-code in Python would be:

x = 0
y = 1
z = 3
mylist = []

if any(v == 0 for v in (x, y, z)):
    mylist.append("c")
if any(v == 1 for v in (x, y, z)):
    mylist.append("d")
if any(v == 2 for v in (x, y, z)):
    mylist.append("e")
if any(v == 3 for v in (x, y, z)):
    mylist.append("f")
0x6upsns

0x6upsns2#


# selection

: a=np.array([0,1,3])                                                                                                                                                 

# options

: np.diag(['c','d','e','f']) 
array([['c', '', '', ''],
       ['', 'd', '', ''],
       ['', '', 'e', ''],
       ['', '', '', 'f']], dtype='<U1')

now we can useaas [row,col] selector, which acts as if any(...) condition :


# list of options[sel,sel]

: np.diag(['c','d','e','f'])[a,a]                                                                                                                                     

 array(['c', 'd', 'f'], dtype='<U1')
xsuvu9jc

xsuvu9jc3#

FIRST, A CORRECTION TO THE OR CONDITIONAL:

You need to say:

if x == 0 or y == 0 or z == 0:

The reason is that "or" splits up the condition into separate logical parts. The way your original statement was written, those parts were:

x
y
z == 0   // or 1, 2, 3 depending on the if statement

The last part was fine --- checking to see if z == 0, for instance --- but the first two parts just said essentially if x and if y. Since integers always evaluate to True unless they're 0, that means the first part of your condition was always True when x or y didn't equal 0 (which in the case of y was always, since you had y = 1, causing your whole condition (because of how OR works) to always be True.

To avoid that, you need to make sure all parts of your condition (each side of the OR) make sense on their own (you can do that by pretending that the other side(s) of the OR statement doesn't exist). That's how you can confirm whether or not your OR condition is correctly defined.

You would write the statements individually like so:

if x == 0
if y == 0
if z == 0

which means the correct mergin with the OR keyword would be:

if x == 0 or y == 0 or z == 0

SECOND, HOW TO SOLVE THE PROBLEM:

You're basically wanting to check to see if any of the variables match a given integer and if so, assign it a letter that matches it in a one-to-one mapping. You want to do that for a certain list of integers so that the output is a list of letters. You'd do that like this:

def func(x, y, z):

    result = []

    for integer, letter in zip([0, 1, 2, 3], ['c', 'd', 'e', 'f']):
        if x == integer or y == integer or z == integer:
            result.append(letter)

    return result

Similarly, you could use LIST COMPREHENSION to achieve the same result faster:

def func(x, y, z):

    return [ 
                letter 
                for integer, letter in zip([0, 1, 2, 3], ['c', 'd', 'e', 'f'])
                if x == integer or y == integer or z == integer
           ]
myss37ts

myss37ts4#

usage without if example:

x,y,z = 0,1,3
values = {0:"c",1:"d",2:"e",3:"f"} # => as if usage
my_list = [values[i] for i in (x,y,z)]

print(my_list)
rxztt3cl

rxztt3cl5#

Here is one more way to do it:

x = 0
y = 1
z = 3
mylist = []

if any(i in [0] for i in[x,y,z]):
    mylist.append("c")
if any(i in [1] for i in[x,y,z]):
    mylist.append("d")
if any(i in [2] for i in[x,y,z]):
    mylist.append("e")
if any(i in [3] for i in[x,y,z]):
    mylist.append("f")

It is a mix oflist comprehensionandanykeyword.

jc3wubiy

jc3wubiy6#

Problem

While the pattern for testing multiple values

>>> 2 in {1, 2, 3}
True
>>> 5 in {1, 2, 3}
False

is very readable and is working in many situation, there is one pitfall:

>>> 0 in {True, False}
True

But we want to have

>>> (0 is True) or (0 is False)
False

Solution

One generalization of the previous expression is based on the answer from ytpillai:

>>> any([0 is True, 0 is False])
False

which can be written as

>>> any(0 is item for item in (True, False))
False

While this expression returns the right result it is not as readable as the first expression :-(

gwo2fgha

gwo2fgha7#

The or does not work like that, as explained by this answer.

While the generic answer would be use

if 0 in (x, y, z):
    ...

this is not the best one for the specific problem. In your case you're doing repeated tests, therefore it is worthwhile to compose a set of these variables:

values = {x, y, z}

if 0 in values:
    mylist.append("c")

if 1 in values:
    mylist.append("d")

We can simplify this using a dictionary - this will result in the same values:

mappings = {0: "c", 1: "d", ...}
for k in mappings:
    if k in values:
        mylist.append(mappings[k])

Or if the ordering of the mylist is arbitrary, you can loop over the values instead and match them to the mappings:

mappings = {0: "c", 1: "d", ...}
for v in (x, y, z):
    if v in mappings:
        mylist.append(mappings[v])
h7wcgrx3

h7wcgrx38#

you can develop it through two ways

def compareVariables(x,y,z):
        mylist = []
        if x==0 or y==0 or z==0:
            mylist.append('c')
        if  x==1 or y==1 or z==1:
            mylist.append('d')
        if  x==2 or y==2 or z==2:
            mylist.append('e')
        if  x==3 or y==3 or z==3:
            mylist.append('f')
        else:
            print("wrong input value!")
        print('first:',mylist)

        compareVariables(1, 3, 2)

Or

def compareVariables(x,y,z):
        mylist = []
        if 0 in (x,y,z):
             mylist.append('c')
        if 1 in (x,y,z):
             mylist.append('d')
        if 2 in (x,y,z):
             mylist.append('e')
        if 3 in (x,y,z):
             mylist.append('f')
        else:
             print("wrong input value!")
        print('second:',mylist)

        compareVariables(1, 3, 2)
mw3dktmi

mw3dktmi9#

You can unite this

x = 0
y = 1
z = 3

in one variable.

In [1]: xyz = (0,1,3,) 
In [2]: mylist = []

Change our conditions as:

In [3]: if 0 in xyz: 
    ...:     mylist.append("c") 
    ...: if 1 in xyz: 
    ...:     mylist.append("d") 
    ...: if 2 in xyz: 
    ...:     mylist.append("e") 
    ...: if 3 in xyz:  
    ...:     mylist.append("f")

Output:

In [21]: mylist                                                                                
Out[21]: ['c', 'd', 'f']
sf6xfgos

sf6xfgos10#

This will help you.

def test_fun(val):
    x = 0
    y = 1
    z = 2
    myList = []
    if val in (x, y, z) and val == 0:
        myList.append("C")
    if val in (x, y, z) and val == 1:
        myList.append("D")
    if val in (x, y, z) and val == 2:
        myList.append("E")

test_fun(2);
ovfsdjhp

ovfsdjhp11#

Without dict, try this solution:

x, y, z = 0, 1, 3    
offset = ord('c')
[chr(i + offset) for i in (x,y,z)]

and gives:

['c', 'd', 'f']
vsaztqbk

vsaztqbk12#

You can use dictionary :

x = 0
y = 1
z = 3
list=[]
dict = {0: 'c', 1: 'd', 2: 'e', 3: 'f'}
if x in dict:
    list.append(dict[x])
else:
    pass

if y in dict:
    list.append(dict[y])
else:
    pass
if z in dict:
    list.append(dict[z])
else:
    pass

print list
qnzebej0

qnzebej013#

Looks like you're building some kind of Caesar cipher.

A much more generalized approach is this:

input_values = (0, 1, 3)
origo = ord('c')
[chr(val + origo) for val in inputs]

outputs

['c', 'd', 'f']

Not sure if it's a desired side effect of your code, but the order of your output will always be sorted.

If this is what you want, the final line can be changed to:

sorted([chr(val + origo) for val in inputs])
eoigrqb6

eoigrqb614#

To test multiple variables with one single value: if 1 in {a,b,c}:

To test multiple values with one variable: if a in {1, 2, 3}:

rbpvctlc

rbpvctlc15#

It can be done easily as

for value in [var1,var2,var3]:
     li.append("targetValue")

相关问题