【问题标题】:Replacing value in list based on input and dictionary ;-;根据输入和字典替换列表中的值;-;
【发布时间】:2021-10-08 10:00:46
【问题描述】:

我需要打印一个 4x4 的表格,水平标记为 (A B C D),垂直标记为 1234,并要求用户在表格中放置一个随机生成的数字(例如 A1、B2)

num = randomly generated number

table = [ [' ', ' ', ' ', ' '],\
            [' ', ' ', ' ', ' '],\
            [' ', ' ', ' ', ' '],\
            [' ', ' ', ' ', ' ']]
ans = input('where would you like to place it?')

我使用字典来分配 A1 : table[0][0] 等等 尝试将值替换为:

if ans in dictionary:
    table.replace(dictionary.get(ans),num)
       

这对我不起作用,但我只知道如何做到这一点。

【问题讨论】:

  • 您是否检查过程序是否输入了您的if 子句?也许您的输入与您的期望不同。尝试在if 中添加print,看看它是否显示在控制台中。
  • 我试试,谢谢! :D

标签: python list dictionary if-statement replace


【解决方案1】:
num = 'randomly generated number'

table = [[' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' ']]

ss = {'B1': [0,1]}
ans = input('where would you like to place it: ')

index_ = ss[ans][0]
columns_ = ss[ans][1]
table[index_][columns_] = num
print(table)

你认为它可以满足你的要求吗?

【讨论】:

  • 非常感谢!! :D 效果很好!!请问是否可以使用嵌套列表而不是字典来做同样的事情?
  • 是的。数组的索引与列表的索引相同。只要索引没问题,就可以用列表或者字典来管理索引。
猜你喜欢
  • 1970-01-01
  • 2020-10-05
  • 2015-10-30
  • 2018-01-10
  • 2021-07-13
  • 1970-01-01
  • 2021-09-18
  • 2021-12-12
  • 2010-11-07
相关资源
最近更新 更多