如何测试多个变量以相对于单个值的平等?

发布于 2025-01-21 09:02:23 字数 361 浏览 0 评论 0 原文

我正在尝试制作一个可以将多个变量与整数进行比较并输出三个字母的函数。我想知道是否有一种将其转化为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"]

I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:

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")

which would return a list of:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

耳钉梦 2025-01-28 09:02:24

在Python中代表您的伪代码的最PYTHONIC方式是:

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")

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")
故事和酒 2025-01-28 09:02:24

可以轻松完成

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

It can be done easily as

for value in [var1,var2,var3]:
     li.append("targetValue")
枯叶蝶 2025-01-28 09:02:24

要测试具有一个单个值的多个变量:如果1 in {a,b,c}:

以一个变量测试多个值:如果a in {1,2,3}:< /代码>

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}:

风轻花落早 2025-01-28 09:02:24

看起来您正在构建某种凯撒密码。

一个更具概括的方法是:

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

输出

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

不确定它是否是代码的所需副作用,但是输出顺序将始终进行分类。

如果这是您想要的,则可以将最后一行更改为:

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

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])
☆獨立☆ 2025-01-28 09:02:24

您可以使用字典:

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

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
浅笑依然 2025-01-28 09:02:24

没有dict,请尝试此解决方案:

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

并给出:

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

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']
我们只是彼此的过ke 2025-01-28 09:02:24

这将帮助您。

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);

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);
卷耳 2025-01-28 09:02:24

您可以将其团结

x = 0
y = 1
z = 3

在一个变量中。

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

将我们的条件更改为:

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") 

输出:

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

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']
薄荷梦 2025-01-28 09:02:24

您可以通过两种方式开发它

    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)

    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)

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)
简美 2025-01-28 09:02:24

无法正常工作,如通过此答案解释

虽然通用答案是使用,

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

但这并不是特定问题的最佳答案。在您的情况下,您正在进行重复测试,因此值得撰写这些变量的 set

values = {x, y, z}

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

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

我们可以使用词典来简化这一点 - 这将导致相同值:

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

或者,如果 myList 的订购是任意的,则可以循环循环 values 并将它们匹配到映射:

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

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])
掩于岁月 2025-01-28 09:02:24

问题

虽然测试多个值的模式

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

非常可读性,并且在许多情况下都可以正常工作,但有一个陷阱:

>>> 0 in {True, False}
True

但是我们希望解决

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

一个

以前的表达式的概括基于 ytpillai

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

可以写成

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

时,当此表达式返回正确的结果时,它不如第一个表达式读取结果:-(

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 :-(

勿挽旧人 2025-01-28 09:02:24

要针对单个值测试多个变量:

将变量包装在设定对象中,例如{a,b,c}。
使用在运算符测试该值是否存储在任何变量中。
如果将值存储在至少一个变量中,则运算符将返回true。

# ✅ test multiple variables against single value using tuple

if 'a' in (a, b, c):
    print('value is stored in at least one of the variables')

# ---------------------------------------------------------

# ✅ test multiple variables against single value using tuple

if 'a' in {a, b, c}:
    print('value is stored in at least one of the variables')

# ---------------------------------------------------------


# ✅ test multiple variables against single value (OR operator chaining)
if a == 'a' or b == 'a' or c == 'a':
    print('value is stored in at least one of the variables')

To test multiple variables against a single value:

Wrap the variables in a set object, e.g. {a, b, c}.
Use the in operator to test if the value is stored in any of the variables.
The in operator will return True if the value is stored in at least one of the variables.

# ✅ test multiple variables against single value using tuple

if 'a' in (a, b, c):
    print('value is stored in at least one of the variables')

# ---------------------------------------------------------

# ✅ test multiple variables against single value using tuple

if 'a' in {a, b, c}:
    print('value is stored in at least one of the variables')

# ---------------------------------------------------------


# ✅ test multiple variables against single value (OR operator chaining)
if a == 'a' or b == 'a' or c == 'a':
    print('value is stored in at least one of the variables')
等你爱我 2025-01-28 09:02:24

这是另一种方法:

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")

它是列表理解 关键字的混合。

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 of list comprehension and any keyword.

悲欢浪云 2025-01-28 09:02:24

使用没有示例的使用:

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)

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)
上课铃就是安魂曲 2025-01-28 09:02:24

首先,对有条件的校正:

您需要说:

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

原因是“或”将条件分为单独的逻辑部分。您的原始语句的写作方式,这些部分是:

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

最后一部分很好---检查是否z == 0,例如---但前两个部分基本上说如果x 如果y 。由于整数始终对 true 进行评估,除非它们为0,否则这意味着您条件的第一部分始终是 true x 时y 不等于0(在y的情况下,由于您有 y = 1 ,因此导致了整个条件(因为>>>>>>> 始终为。

为了避免 通过假装不存在语句的另一面,这是您可以确认您的条件是否正确定义的方式。

您会单独编写陈述:

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

这意味着使用关键字的正确MERGIN是:

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

第二,如何解决问题:

您基本上想检查以查看是否有任何变量匹配给定的整数,如果是的话,请分配一个字母,以一对一的映射匹配它。您想为某些整数列表做到这一点,以便输出是字母列表。您会这​​样做:

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
        

同样,您可以使用列表理解来更快地达到相同的结果:

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
           ]
    
    

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
           ]
    
    
那小子欠揍 2025-01-28 09:02:23

您误解了布尔表达方式;他们不像英语句子那样工作,猜猜您在这里谈论的所有名称都相同的比较。您正在寻找:

if x == 1 or y == 1 or z == 1:

x y 另有自己评估( false ,如果 0 ,,> true 否则)。

您可以使用针对

if 1 in (x, y, z):

或者仍然更好:

if 1 in {x, y, z}:

使用要利用恒定成本的会员测试(中的,无论左手操作数是什么时间)。

说明

当您使用时,Python将操作员的每一侧视为 extair 表达式。表达式 x或y == 1 首先将其视为 x 的布尔测试,然后如果是false,则表达式 y == 1 已测试。

这是由于操作员优先操作员的优先级低于 == 测试,因此对后者进行了评估 first

但是,即使不是不是 ,并且表达式 x或y或z == 1 实际上也被解释为(x或y或z)= = 1 而是,这仍然不会做您期望的事情。

X或Y或Z 将评估第一个参数,例如“真实”,例如 false ,数字0或空(见 boolean Expressions 有关python在布尔语境中认为false的详细信息)。

因此,对于值 x = 2; y = 1; z = 0 x或y或z 将解析为 2 ,因为这是参数中的第一个真实值。然后 2 == 1 将是 false ,即使 y == 1 将是 true

相反的情况也适用;针对单个变量测试多个值; x == 1或2或3 由于相同的原因而失败。使用 x == 1或x == 2或x == 3 x in {1,2,3}

You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:

if x == 1 or y == 1 or z == 1:

x and y are otherwise evaluated on their own (False if 0, True otherwise).

You can shorten that using a containment test against a tuple:

if 1 in (x, y, z):

or better still:

if 1 in {x, y, z}:

using a set to take advantage of the constant-cost membership test (i.e. in takes a fixed amount of time whatever the left-hand operand is).

Explanation

When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.

This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.

However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.

x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).

So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.

The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.

A君 2025-01-28 09:02:23

使用类似的字典结构更容易解决您的问题:

x = 0
y = 1
z = 3
d = {0: 'c', 1:'d', 2:'e', 3:'f'}
mylist = [d[k] for k in [x, y, z]]

Your problem is more easily addressed with a dictionary structure like:

x = 0
y = 1
z = 3
d = {0: 'c', 1:'d', 2:'e', 3:'f'}
mylist = [d[k] for k in [x, y, z]]
李白 2025-01-28 09:02:23

正如Martijn Pieters所说的,正确,最快的格式是:

if 1 in {x, y, z}:

使用他的建议,您现在将拥有单独的IF statement 。例如:

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")
...

这将起作用,但是如果您很舒服使用词典(请参阅我在那里所做的),您可以通过制作初始字典将数字映射到您想要的字母中来清理此操作,然后使用循环:

num_to_letters = {0: "c", 1: "d", 2: "e", 3: "f"}
for number in num_to_letters:
    if number in {x, y, z}:
        mylist.append(num_to_letters[number])

As stated by Martijn Pieters, the correct, and fastest, format is:

if 1 in {x, y, z}:

Using his advice you would now have separate if-statements so that Python will read each statement whether the former were True or False. Such as:

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")
...

This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:

num_to_letters = {0: "c", 1: "d", 2: "e", 3: "f"}
for number in num_to_letters:
    if number in {x, y, z}:
        mylist.append(num_to_letters[number])
找个人就嫁了吧 2025-01-28 09:02:23

编写 X或Y或Z == 0 的直接方法是,

if any(map((lambda value: value == 0), (x,y,z))):
    pass # write your logic.

但我不认为,您喜欢它。 :)
这种方式很丑陋。

另一种方式(更好)是:

0 in (x, y, z)

btw很多如果可以写成这样的东西

my_cases = {
    0: Mylist.append("c"),
    1: Mylist.append("d")
    # ..
}

for key in my_cases:
    if key in (x,y,z):
        my_cases[key]()
        break

The direct way to write x or y or z == 0 is

if any(map((lambda value: value == 0), (x,y,z))):
    pass # write your logic.

But I dont think, you like it. :)
And this way is ugly.

The other way (a better) is:

0 in (x, y, z)

BTW lots of ifs could be written as something like this

my_cases = {
    0: Mylist.append("c"),
    1: Mylist.append("d")
    # ..
}

for key in my_cases:
    if key in (x,y,z):
        my_cases[key]()
        break
木森分化 2025-01-28 09:02:23

要检查一个值是否包含在一组变量中,您可以使用内置模块 itertools operator 。

例如:

导入:

from itertools import repeat
from operator import contains

声明变量:

x = 0
y = 1
z = 3

创建值的映射(按照要检查的顺序):

check_values = (0, 1, 3)

使用 itertools 允许重复变量:

check_vars = repeat((x, y, z))

最后,使用 map 创建迭代器的函数:

checker = map(contains, check_vars, check_values)

然后,在检查值(按原始顺序)检查时,请使用 next()

if next(checker)  # Checks for 0
    # Do something
    pass
elif next(checker)  # Checks for 1
    # Do something
    pass

etc ...

这比 lambda x:x in (变量)因为操作员是一个内置的模块,比使用 lambda 必须更快,更有效,该模块必须创建一个自定义的原位功能。

检查列表中是否有非零(或false)值的另一个选项:

not (x and y and z)

等效:

not all((x, y, z))

To check if a value is contained within a set of variables you can use the inbuilt modules itertools and operator.

For example:

Imports:

from itertools import repeat
from operator import contains

Declare variables:

x = 0
y = 1
z = 3

Create mapping of values (in the order you want to check):

check_values = (0, 1, 3)

Use itertools to allow repetition of the variables:

check_vars = repeat((x, y, z))

Finally, use the map function to create an iterator:

checker = map(contains, check_vars, check_values)

Then, when checking for the values (in the original order), use next():

if next(checker)  # Checks for 0
    # Do something
    pass
elif next(checker)  # Checks for 1
    # Do something
    pass

etc...

This has an advantage over the lambda x: x in (variables) because operator is an inbuilt module and is faster and more efficient than using lambda which has to create a custom in-place function.

Another option for checking if there is a non-zero (or False) value in a list:

not (x and y and z)

Equivalent:

not all((x, y, z))
鲜肉鲜肉永远不皱 2025-01-28 09:02:23

如果您非常懒惰,则可以将这些值放入数组中。例如,

list = []
list.append(x)
list.append(y)
list.append(z)
nums = [add numbers here]
letters = [add corresponding letters here]
for index in range(len(nums)):
    for obj in list:
        if obj == num[index]:
            MyList.append(letters[index])
            break

您也可以将数字和字母放在字典中并做到这一点,但这可能比简单地说陈述要复杂得多。这就是您尝试变得更加懒惰的方法:)

还有一件事,您的

if x or y or z == 0:

遗嘱会汇编,但不是您想要的。当您简单地将变量放在if语句(示例)中时,

if b

程序将检查该变量是否不是null。编写上述语句(更有意义)的另一种方法是

if bool(b)

Bool是Python中的内置函数,它基本上可以验证Boolean语句(如果您不知道那是什么,那就是您要制作的内容在您现在的IF语句中:))

我发现的另一种懒惰方式是:

if any([x==0, y==0, z==0])

If you ARE very very lazy, you can put the values inside an array. Such as

list = []
list.append(x)
list.append(y)
list.append(z)
nums = [add numbers here]
letters = [add corresponding letters here]
for index in range(len(nums)):
    for obj in list:
        if obj == num[index]:
            MyList.append(letters[index])
            break

You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)

One more thing, your

if x or y or z == 0:

will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)

if b

the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is

if bool(b)

Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))

Another lazy way I found is :

if any([x==0, y==0, z==0])
知足的幸福 2025-01-28 09:02:23

设置是这里的好方法,因为它订购了变量,在这里似乎是您的目标。 {z,y,x} {0,1,3} 无论参数的顺序如何。

>>> ["cdef"[i] for i in {z,x,y}]
['c', 'd', 'f']

这样,整个解决方案是o(n)。

Set is the good approach here, because it orders the variables, what seems to be your goal here. {z,y,x} is {0,1,3} whatever the order of the parameters.

>>> ["cdef"[i] for i in {z,x,y}]
['c', 'd', 'f']

This way, the whole solution is O(n).

骷髅 2025-01-28 09:02:23

我认为这将更好地处理:

my_dict = {0: "c", 1: "d", 2: "e", 3: "f"}

def validate(x, y, z):
    for ele in [x, y, z]:
        if ele in my_dict.keys():
            return my_dict[ele]

输出:

print validate(0, 8, 9)
c
print validate(9, 8, 9)
None
print validate(9, 8, 2)
e

I think this will handle it better:

my_dict = {0: "c", 1: "d", 2: "e", 3: "f"}

def validate(x, y, z):
    for ele in [x, y, z]:
        if ele in my_dict.keys():
            return my_dict[ele]

Output:

print validate(0, 8, 9)
c
print validate(9, 8, 9)
None
print validate(9, 8, 2)
e
隱形的亼 2025-01-28 09:02:23

如果您想使用,则以下是另一种解决方案:

myList = []
aList = [0, 1, 3]

for l in aList:
    if l==0: myList.append('c')
    elif l==1: myList.append('d')
    elif l==2: myList.append('e')
    elif l==3: myList.append('f')

print(myList)

If you want to use if, else statements following is another solution:

myList = []
aList = [0, 1, 3]

for l in aList:
    if l==0: myList.append('c')
    elif l==1: myList.append('d')
    elif l==2: myList.append('e')
    elif l==3: myList.append('f')

print(myList)
烟花易冷人易散 2025-01-28 09:02:23

此处提供的所有出色答案都集中在原始海报的具体要求上,并集中于
{x,y,z} in {x,y,z} 的解决方案。
他们忽略的是这个问题的更广泛含义:
如何针对多个值测试一个变量?
如果使用字符串,则提供的解决方案对部分命中无效:
测试字符串“野生”是否在多个值中

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in {x, y, z}: print (True)
... 

,或者

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in [x, y, z]: print (True)
... 

在这种情况下,最容易转换为字符串,

>>> [x, y, z]
['Wild things', 'throttle it back', 'in the beginning']
>>> {x, y, z}
{'in the beginning', 'throttle it back', 'Wild things'}
>>> 

>>> if "Wild" in str([x, y, z]): print (True)
... 
True
>>> if "Wild" in str({x, y, z}): print (True)
... 
True

则应注意,如 @codeforester 所述,该方法范围丢失了此方法,如:

>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
... 
True

3个字母 rot 确实存在于列表中,但不是单个单词。对“腐烂”的测试将失败,但是如果列表项目之一是“地狱中的腐烂”,那也将失败。
结果是,如果使用此方法,请注意您的搜索标准,并注意它确实有此限制。

All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the if 1 in {x,y,z} solution put forward by Martijn Pieters.
What they ignore is the broader implication of the question:
How do I test one variable against multiple values?
The solution provided will not work for partial hits if using strings for example:
Test if the string "Wild" is in multiple values

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in {x, y, z}: print (True)
... 

or

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in [x, y, z]: print (True)
... 

for this scenario it's easiest to convert to a string

>>> [x, y, z]
['Wild things', 'throttle it back', 'in the beginning']
>>> {x, y, z}
{'in the beginning', 'throttle it back', 'Wild things'}
>>> 

>>> if "Wild" in str([x, y, z]): print (True)
... 
True
>>> if "Wild" in str({x, y, z}): print (True)
... 
True

It should be noted however, as mentioned by @codeforester, that word boundries are lost with this method, as in:

>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
... 
True

the 3 letters rot do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.
The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.

岁吢 2025-01-28 09:02:23
d = {0:'c', 1:'d', 2:'e', 3: 'f'}
x, y, z = (0, 1, 3)
print [v for (k,v) in d.items() if x==k or y==k or z==k]
d = {0:'c', 1:'d', 2:'e', 3: 'f'}
x, y, z = (0, 1, 3)
print [v for (k,v) in d.items() if x==k or y==k or z==k]
羁绊已千年 2025-01-28 09:02:23

此代码可能会有所帮助

L ={x, y, z}
T= ((0,"c"),(1,"d"),(2,"e"),(3,"f"),)
List2=[]
for t in T :
if t[0] in L :
    List2.append(t[1])
    break;

This code may be helpful

L ={x, y, z}
T= ((0,"c"),(1,"d"),(2,"e"),(3,"f"),)
List2=[]
for t in T :
if t[0] in L :
    List2.append(t[1])
    break;
晒暮凉 2025-01-28 09:02:23

您可以尝试下面显示的方法。在此方法中,您将可以自由地指定/输入要输入的变量数量。

mydict = {0:"c", 1:"d", 2:"e", 3:"f"}
mylist= []

num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

for i in range(num_var): 
    ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
    globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
    mylist += mydict[globals()['var'+str('i').zfill(3)]]

print mylist
>>> ['c', 'd', 'f']

You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.

mydict = {0:"c", 1:"d", 2:"e", 3:"f"}
mylist= []

num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

for i in range(num_var): 
    ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
    globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
    mylist += mydict[globals()['var'+str('i').zfill(3)]]

print mylist
>>> ['c', 'd', 'f']
执手闯天涯 2025-01-28 09:02:23

一条解决方案:

mylist = [{0: 'c', 1: 'd', 2: 'e', 3: 'f'}[i] for i in [0, 1, 2, 3] if i in (x, y, z)]

或:

mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]

One line solution:

mylist = [{0: 'c', 1: 'd', 2: 'e', 3: 'f'}[i] for i in [0, 1, 2, 3] if i in (x, y, z)]

Or:

mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]
夜司空 2025-01-28 09:02:23

也许您需要直接公式来设置输出位。

x=0 or y=0 or z=0   is equivalent to x*y*z = 0

x=1 or y=1 or z=1   is equivalent to (x-1)*(y-1)*(z-1)=0

x=2 or y=2 or z=2   is equivalent to (x-2)*(y-2)*(z-2)=0

让我们映射到位:'c':1'D':0xB10'e':0xB100'f':0xb1000

isc的关系(is'c'):

if xyz=0 then isc=1 else isc=0

如果公式

[c]: (xyz = 0和isc = 1)或(((((xyz = 0 andc = 1))或(isc = 0))和(isc = 0))

[d]:( (x-1)(y-1)(z-1)= 0和isc = 2)或((((xyz = 0 and isd = 2))或(isc = 0))和(isc = 0))

...

通过以下逻辑来连接这些公式:

  • 逻辑是方程式
  • 逻辑是方程的产物

,您将拥有一个总方程式
express sum,您拥有总和的总公式

,然后总和1是c,sum&amp; 2 is d,sum&amp; 4 is e,sum&amp; 5 is f eft eft

efter the之后,您可以形成预定义的数组。

array [sum] 为您提供字符串。

Maybe you need direct formula for output bits set.

x=0 or y=0 or z=0   is equivalent to x*y*z = 0

x=1 or y=1 or z=1   is equivalent to (x-1)*(y-1)*(z-1)=0

x=2 or y=2 or z=2   is equivalent to (x-2)*(y-2)*(z-2)=0

Let's map to bits: 'c':1 'd':0xb10 'e':0xb100 'f':0xb1000

Relation of isc (is 'c'):

if xyz=0 then isc=1 else isc=0

Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315

[c]: (xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))

[d]: ((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))

...

Connect these formulas by following logic:

  • logic and is the sum of squares of equations
  • logic or is the product of equations

and you'll have a total equation
express sum and you have total formula of sum

then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f

After this you may form predefined array where index of string elements would correspond to ready string.

array[sum] gives you the string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文