Python 如何优雅地存储非唯一值的位置矩阵
我试图最终用Pygame创建一个矩阵风格的雨代码动画 我被困在开头,我想为每个角色分配坐标,因为: 我不能在dict中有重复的键,因此此结构不起作用:Python 如何优雅地存储非唯一值的位置矩阵,python,Python,我试图最终用Pygame创建一个矩阵风格的雨代码动画 我被困在开头,我想为每个角色分配坐标,因为: 我不能在dict中有重复的键,因此此结构不起作用: CharacterMatrix = {character : [xPos, yPos]} CharacterMatrix = {[xPos, yPos] : character } 但我也不能将唯一坐标作为键,因为dict不接受列表作为键,所以这当然也不起作用: CharacterMatrix = {character : [xPos,
CharacterMatrix = {character : [xPos, yPos]}
CharacterMatrix = {[xPos, yPos] : character }
但我也不能将唯一坐标作为键,因为dict不接受列表作为键,所以这当然也不起作用:
CharacterMatrix = {character : [xPos, yPos]}
CharacterMatrix = {[xPos, yPos] : character }
我现在的问题是:如何优雅地存储大量具有相应x和y坐标的非唯一随机字符
非常感谢,如果我监督了一个类似的问题,我很抱歉 在python中,dict接受不可变类型作为键,因此使用tuple而不是list 编辑 例如:
您不存储矩阵,而是将列存储为“句子”,使用
zip
创建行:
c = ["SHOW", "ME ", "THIS"]
r = [' '.join(row) for row in zip(*c)]
print (c)
for n in r:
print(n)
输出:
['SHOW', 'ME ', 'THIS']
S M T
H E H
O I
W S
现在,您只需改变内容-您可以分割字符串:
c[1] = "!"+c[1][:-1]
r = [' '.join(row) for row in zip(*c)]
for n in r:
print(n)
输出:
S ! T
H M H
O E I
W S
矩阵会很麻烦,您需要向下滚动单个列,而其他列则静止不动,可能需要替换单个字符。使用矩阵将需要您一直降低很多,修改“列语句”(如上所述)或字符串列表要容易得多:
from string import ascii_letters, digits
from itertools import product
import random
import os
import time
random.seed(42) # remove for more randomness
numCols = 10
numRows = 20
allCoods = list(product(range(numCols),range(numRows))) # for single char replacement
pri = ascii_letters + digits + '`?=)(/&%$§"!´~#' # thats what we display
# cred: https://stackoverflow.com/a/684344/7505395
def cls():
os.system('cls' if os.name=='nt' else 'clear')
def modCol(columns, which):
for (c,r) in which:
# replace change random characters
newOne = random.choice(pri)
columns[c] = columns[c][:r]+[newOne]+columns[c][r+1:]
for i in range(len(columns)):
if (random.randint(0,5) > 2):
# scroll some lines down by 1
columns[i].insert(0,random.choice(pri))
columns[i] = columns[i][:-1]
# creates random data for columns
cols = [random.choices(pri ,k=numRows ) for _ in range(numCols)]
while True:
cls()
# zip changes your columns-list into a row-tuple, the joins for printing
print ( '\n'.join(' '.join(row) for row in zip(*cols)))
time.sleep(1)
# which characters to change?
choi = random.choices(allCoods, k=random.randint(0,(numCols*numRows)//3))
modCol(cols, choi )