Python的检查清单中的产品可免费 [英] Python Check if item in list is free

查看:84
本文介绍了Python的检查清单中的产品可免费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个阵列,包含9字符变量。我使用循环打印他们的3连胜。我想,以检查是否在2行3的变量是相同的,并创建功能,这将改变第三个相匹配的其他人。

我想垂直和水平方向做两个。
我一定要改变我的阵列二维数组
这将让我改变近一半的code的
是否有机会,我就不必手动编写如果语句是这样的:

I've got an array, that contains 9 char variables. I print them in a row of 3 using for loop. I would like to check if 2 of 3 variables in a row are the same and create function that will change the third one to match the others.
I would like to do it both vertically and horizontally.
Do i have to change my array into 2D array?
It would made me to change nearly half of the code.
Is there a chance that i wouldn't have to write the if statements manually like this:

if array[0] == array[1]:
    change the_third_var
elif array[1] == array[2]:
    change the_first_var
elif array[0] == array[2]:
    change the_sec_var

但它会检查它会自动使用或任何其他循环?

将解决方案帮我简化低于code(可选)?

but it will check it automatically using for or any other loop?
Will the solution help me to simplify the code below (optional)?

def check_winner(pl_array, player_choice, computer_choice):
    vertical = [2, 5, 8]
    diagonal = [6, 7, 8]
    # checking vertical lines
    for each in vertical:
        if pl_array[each - 2] == pl_array[each - 1] == pl_array[each]:
            if pl_array[each] == player_choice or pl_array[each] == computer_choice:
                return True
    # checking diagonal lines
    for every in diagonal:
        if pl_array[every - 6] == pl_array[every - 3] == pl_array[every]:
            if pl_array[every] == player_choice or pl_array[every] == computer_choice:
                return True
    # across
    if pl_array[8] == pl_array[4] == pl_array[0]:
        if pl_array[8] == player_choice or pl_array[8] == computer_choice:
            return True
    elif pl_array[6] == pl_array[4] == pl_array[2]:
        if pl_array[6] == player_choice or pl_array[2] == computer_choice:
            return True
    else:
        return False

任何帮助AP preciated。

Any help appreciated.

推荐答案

尽管这是一个有点冗长我宁愿你贴比任何其他选项,如果/ ELIF逻辑。你可以用它在功能和简单的调用它,每当你需要这将减少code的量。

Even though it's a little verbose I rather have the if/elif logic you posted than any other option. You can wrap it in a function and simply call it whenever you need which will reduce the amount of code.

这是说,你还可以做下面的丑陋的东西:

That said, you can also do the following ugly thing:

for i in range(-1, 2):
    if arr[i-1] == arr[i]:
        arr[i+1] = arr[i]

这篇关于Python的检查清单中的产品可免费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆