反正有没有在范围函数中使这个代码,所以我不必重复100次?

时间:2018-03-16 07:14:41

标签: python-3.x range

我正在制作一个程序来使用' x'但对于每个输入,我将不得不复制出来:

if input() == 'a0':
    L0[1] = 'x'
    print('\n')
    all()

100次,如果我想添加一种删除' x'的方法,那么即使是100次, 有什么方法可以使用范围函数或任何东西缩短该过程吗?

Tl = ['/','a','b','c','d','e','f','g','h','i','j']
L0 = ['0','.','.','.','.','.','.','.','.','.','.']
L1 = ['1','.','.','.','.','.','.','.','.','.','.']
L2 = ['2','.','.','.','.','.','.','.','.','.','.']
L3 = ['3','.','.','.','.','.','.','.','.','.','.']
L4 = ['4','.','.','.','.','.','.','.','.','.','.']
L5 = ['5','.','.','.','.','.','.','.','.','.','.']
L6 = ['6','.','.','.','.','.','.','.','.','.','.']
L7 = ['7','.','.','.','.','.','.','.','.','.','.']
L8 = ['8','.','.','.','.','.','.','.','.','.','.']
L9 = ['9','.','.','.','.','.','.','.','.','.','.']
def all():
    print(*Tl)
    print(*L0)
    print(*L1)
    print(*L2)
    print(*L3)
    print(*L4)
    print(*L5)
    print(*L6) 
    print(*L7)
    print(*L8)
    print(*L9)
all()
print('\nenter coordinates to draw')
if input() == 'a0':
    L0[1] = 'x'
    print('\n')
    all()

我已经考虑了这个并进行了搜索,但我不知道我将如何做到这一点,谢谢

3 个答案:

答案 0 :(得分:1)

正如上面的评论中所建议的那样,您应该从数据存储中分割打印信息。

第一种方法是创建list list s。

def create_empty_table():
    return [
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.','.','.','.'],
    ]

def print_table(table):
    print("/ a b c d e f g h i j")
    for n, line in enumerate(table):
        print(n, " ".join(line))
    print()

if __name__ == '__main__':
    table = create_empty_table()
    # The following part should probably go inside a loop to let the users introduce several values and not just one
    print_table(table)
    user_value = input("Enter coordinates to draw: ")  # Ask the user for the input
    letter = user_value[0]  # Extract the first char
    number = user_value[1]  # Extract the second char
    col = ord(letter) - ord("a")  # Transform the letter into an integer
    row = int(number)  # Transform the numbr into an int
    table[row][col] = 'x'
    print_table(table)

数字字符串可以直接用int('0')转换为int,但字母有点复杂。 builtin ord function返回字符的unicode点表示。通过减去'a'(97)的unicode点表示,我们得到了一个可以在列表中使用的索引:ord('a') - ord('a') == 0ord('b') - ord('a') == 1ord('c') - ord('a') == 2,...

有几件事可以加强。编辑......

接受大写字母非常容易。如果您想自己尝试,请查看str.lower method,或者继续使用下一个示例,因为它使用此方法。

表格的非硬编码大小将是另一项改进。现在我们将最大行数和列数分别保持在10和26,因为有10个数字和26个字母。接受更高的上限将在稍后进行。

另一个重要的变化是处理用户输入。我们将使用例外。

def create_empty_table(rows=10, cols=10, *, fill_char='.'):
    table = []
    for i in range(rows):                 # Create the specified number of rows
        table.append([fill_char] * cols)  # and the specified number of cols
    return table

def print_table(table):
    if len(table) == 0:  # If the table had no row and no column
        return           # we return to avoid errors
    header = "/"
    for i in range(ord("a"), ord("a") + len(table[0]):  # len(table[0]) == number of cols
        header += " " + chr(i)
    print(header)
    for n, line in enumerate(table):
        print(n, " ".join(line))
    print()

if __name__ == '__main__':
    table = create_empty_table()
    # The following part should probably go inside a loop to let the users introduce several values and not just one
    print_table(table)
    while True:
        user_value = input("Enter coordinates to draw: ")  # Ask the user for the input
        try:
            letter = user_value[0]  # Extract the first char
            number = user_value[1]  # Extract the second char
        except IndexError:  # The user did not introduce two characters
            print("ERRROR: use 'a0' notation to introduce the coordinates!")
            continue  # Go back to the beggining of the loop again

        col = ord(letter.lower()) - ord("a")  # Transform the letter into an integer
        row = int(number)  # Transform the numbr into an int
        try:
            table[row][col] = 'x'
        except IndexError:  # He introduced wrong values
            print("ERROR: Wrong input!")
            continue

        break  # Get out of the while True infinite loop if we have gotten this far
    print_table(table)

builtin chr methodord相反,它从点(整数)返回符号。

强大的代码需要进一步验证,例如检测第一个字符不是字母或第二个字符不是数字,检测他是否引入了超过2个字符,...

答案 1 :(得分:1)

编辑:如果您已在代码中的某处导入pandas,则可以利用它来解决当前查询。 如果您刚刚开始执行数据处理/分析或处理矩阵的大型程序,您可能想要检查熊猫的功能。 如果您的情况不属于上述情况,请使用Adirio's answer

使用pandas,我们创建了一个类似于可修改矩阵的数据框。我们最初使用'。'填充它。 &安培;随后,当usr输入到达时,将它们更改为'x'。 我编写了这个程序,只要它们被空格分隔,就可以接受多个字段更改为'x'。 你可以进一步修改这个程序,用你想要的多种符号来修改这个矩阵。

import pandas as pd

canvas = pd.DataFrame()
for z in 'abcdefghij':
    canvas = pd.concat([canvas,pd.DataFrame(['.','.','.','.','.','.','.','.','.','.'],columns=list(z))],axis=1)

print('\nenter coordinates to draw')
usr_input = input()

for i in usr_input.split():
    c,r = list(i)
    r = int(r)
    canvas.at[r,c] = 'x'

print('\n')
print(canvas)

输出:

enter coordinates to draw
a1 b2 c3

   a  b  c  d  e  f  g  h  i  j
0  .  .  .  .  .  .  .  .  .  .
1  x  .  .  .  .  .  .  .  .  .
2  .  x  .  .  .  .  .  .  .  .
3  .  .  x  .  .  .  .  .  .  .
4  .  .  .  .  .  .  .  .  .  .
5  .  .  .  .  .  .  .  .  .  .
6  .  .  .  .  .  .  .  .  .  .
7  .  .  .  .  .  .  .  .  .  .
8  .  .  .  .  .  .  .  .  .  .
9  .  .  .  .  .  .  .  .  .  .

答案 2 :(得分:0)

你可以通过在一组中只存储“绘制”的坐标来简化它 - 或者去一本字典,并在那个坐标上存储什么样的痛苦。

基本上,你只存储玩家/坐标被占用的位置。如果没有占用坐标,则在网格中绘制一个“空”,否则绘制其内容:

玩家轮流场的示例:

  import os # clear console

  def cls():
      """Clears the console."""
      os.system('cls' if os.name=='nt' else 'clear')

  # playground definitions
  cols = [x for x in "abcdefghij"]     # column headers
  rows = [x for x in range(10)]        # row "headers"
  rowsString = [str(x) for x in rows]  # convenience

  # dictionary holding whats in what cell
  field = {}

  def printAll(d):
    """Clears the screen, prints d. Non-provided keys are printed as '.'""" 
    cls()
    print("   ", ' '.join(cols))        # print column headers 
    for rowNum in rows:
      print(f' {rowNum:d} ', end = " ") # print row header
      for c in cols:
        key = (c,rowNum)                # check if in dict, print value else '.'
        if key in d:
          print(f'{d[key]}', end = " ")
        else:
          print(".", end = " ")
      print()

  player = ["X","O"]
  turn = 0
  while True:
    printAll(field)     # inital field printing
    p = player[turn%2]  # who is it this turn?
    coord = ""
    print("'q' quits, 'r' resets")

    # repeat until valid input
    while len(coord)!= 2 or coord[0] not in cols or coord[1] not in rowsString:
      coord = input(f'Player {p} - enter coords: ')
      if coord=="q":
        exit()
      elif coord =="r":
        field = {}
        printAll(field)
        print("'q' quits, 'r' resets")
      elif len(coord)== 2 and (coord[0],int(coord[1])) in field:
        print("Already placed. Choose new coords.")
        coord=""

    # store coord with players symbol - if you only draw lines, simplify code w/o playrs
    field[(coord[0],int(coord[1]))] = p
    turn+=1

转弯后输出:

    a b c d e f g h i j
 0  . . . . . . . . . .
 1  . . . . . . . . . .
 2  . . . . . . . . . .
 3  . O X . . O . . . .
 4  X . . . . X . . . .
 5  X . . . . O . . . .
 6  . . . . . . . . . .
 7  . . . . . . . . . .
 8  . . . . . . . . X .
 9  O . O . . . . . . .
'q' quits, 'r' resets
Player X - enter coords: c99
Player X - enter coords: b33
Player X - enter coords: abdc
Player X - enter coords: hallo
Player X - enter coords: 34
Player X - enter coords:

要仅打印X并再次删除它们,请将主程序更改为:

while True:
  printAll(field) # inital field printing
  coord = ""
  print("'q' quits, 'r' resets")
  while len(coord)!= 2 or coord[0] not in cols or coord[1] not in rowsString:
    coord = input(f'Enter coords: ')
    if coord=="q":
      exit()
    elif coord =="r":
      field = {}
      printAll(field)
      print("'q' quits, 'r' resets")

  # set or delete field depending on if it is already set or not:
  if len(coord)== 2 and (coord[0],int(coord[1])) in field:
    field.pop((coord[0],int(coord[1])))
  else:
    field[(coord[0],int(coord[1]))] = 'X'