如何缩短很多if语句? (Python 3.x)

时间:2017-03-09 15:46:10

标签: python-3.x

如何缩短Number of squares: 4 Note: Start values is from 0 -> n-1 0,0 is at top left side X start value: 0 Y start value: 0 x:0, y:0 (2r,1d)moving to x:2, y:1 x:1, y:0 (2r,1d)moving to x:3, y:1 x:0, y:1 (2r,1d)moving to x:2, y:2 x:1, y:1 (2r,1u)moving to x:3, y:0 x:1, y:1 (2r,1d)moving to x:3, y:2 x:1, y:2 (2r,1d)moving to x:3, y:3 X: 0, Y: 0. Moving 2 Right, 1 Down X: 2, Y: 1. Moving 2 Left, 1 Down X: 0, Y: 2. Moving 2 Up, 1 Right X: 1, Y: 0. Moving 2 Right, 1 Down X: 3, Y: 1. Moving 2 Left, 1 Down X: 1, Y: 2. Moving 2 Up, 1 Right X: 2, Y: 0. Moving 2 Left, 1 Down X: 0, Y: 1. Moving 2 Right, 1 Down X: 2, Y: 2. Moving 2 Left, 1 Down X: 0, Y: 3. Moving 2 Up, 1 Right X: 1, Y: 1. Moving 2 Right, 1 Up X: 1, Y: 1. Moving 2 Right, 1 Down X: 3, Y: 2. Moving 2 Left, 1 Down X: 1, Y: 1. Moving 2 Down, 1 Right X: 1, Y: 2. Moving 2 Right, 1 Down Did not find any way to complete Knights Tour! 1 4 7 12 8 11 2 5 3 6 9 13 10 14 15 16 循环中的所有if语句?我正在为一个大学项目开发​​这个。我想不出办法。

基本上它应该做的是,如果板上的某个位置不等于岩石,则将其设置为植物。这些位置是工厂周围的一个圆圈。例如:

N N N
N P N
N N N

for

2 个答案:

答案 0 :(得分:2)

是的,将您的索引排列放在一个列表中并对其进行迭代。您可以明确定义列表(对于初学者更易读,但更容易出错)或者通过理解生成它。首先明确版本:

coord_shift = [(1, 0), (-1, 0), (1, 1), (-1, -1), (0, 1), (0, -1), (1, -1), (-1, 1)]
for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
        if Field[Row][Column] == PLANT:
            for i, j in coord_shift:
                if Field[Row + i][Column + j] != ROCKS:
                    Field[Row + i][Column + j] = GOODSUMMER

一些补充说明:

推荐的Python样式是对常规变量使用小写变量名,大写字母更适用于类。

你不需要休息。

以上内容抓住了Field[Row +1][Column -1]的小错误。

我承诺的冒险版本是:

coord_shift = [(i, j) for i in range(-1, 2) for j in range (-1, 2)]
coord_shift.drop((0, 0))

答案 1 :(得分:1)

我们只能猜测您的其余代码,因此下面列出的是用于测试目的的完整实现。要查看重新设计的代码,请查看multiply_plants功能。它使用循环来检查单元格周围的区域,而不是使用许多if语句。您可能还注意到正确检查每个列表的边界,以便不会发生IndexError个异常。

#! /usr/bin/env python3
import random


FIELD_ROWS = 10
FIELD_COLUMNS = 10
EMPTY = ' '
PLANT = 'P'
ROCKS = 'R'
NEW_PLANT = 'N'


def main():
    field = create_field()
    show_field(field)
    multiply_plants(field, 2)
    replace_cells(field, NEW_PLANT, PLANT)
    show_field(field)


def create_field():
    field = []
    for _ in range(FIELD_ROWS):
        row = []
        for _ in range(FIELD_COLUMNS):
            row.append(random.choice([EMPTY] * 3 + [ROCKS] * 2 + [PLANT] * 1))
        field.append(row)
    return field


def show_field(field):
    width = max(map(len, field)) * 2 + 1
    print(f'/{"-" * width}\\')
    print('\n'.join(' '.join(['|'] + row + ['|']) for row in field))
    print(f'\\{"-" * width}/')


def multiply_plants(field, rainfall):
    # If there was enough rain, cause the plants to spread.
    if rainfall > 1:
        print('This summer has been a perfect summer;')
        print('the plants have multiplied!')
        # Find each space that already has a plant in it.
        for y, row in enumerate(field):
            for x, cell in enumerate(row):
                if cell == PLANT:
                    # Introduce a Y-axis offset to search up & down.
                    for y_offset in range(-1, 2):
                        y_index = y_offset + y
                        if 0 <= y_index < len(field):
                            # Introduce a X-axis offset to search left & right.
                            for x_offset in range(-1, 2):
                                if y_offset or x_offset:    # Skip zero offset.
                                    x_index = x_offset + x
                                    if 0 <= x_index < len(field[y_index]):
                                        # Spread plant to non-rock areas.
                                        if field[y_index][x_index] != ROCKS:
                                            field[y_index][x_index] = NEW_PLANT


def replace_cells(field, old, new):
    for y, row in enumerate(field):
        for x, cell in enumerate(row):
            if cell == old:
                field[y][x] = new


if __name__ == '__main__':
    main()