编写一个手动循环来搜索一个列表会使事情过于复杂。编写两个循环来搜索两个字符串列表,并试图将它们混合在一起,同时循环索引其他的东西,难怪你会迷惑自己。
让我们放弃它,改用一些字典:
columns = {'apple': 1, 'lemon': 2, 'pear': 3}
rows = {'red': 1, 'yellow': 2, 'green': 3}
现在,如果您想知道要放入哪个矩阵元素,就没有循环,只有两个dict查找:
>>> (colname, rowname), value = [["apple", "red"], " 1 "]
>>> columns[colname]
1
>>> rows[rowname]
1
所以,现在我们要做的就是从一个空矩阵开始:
matrix = [
['///', 'apple', 'lemon', 'pear'],
['red', 0, 0, 0],
['yellow', 0, 0, 0],
['green', 0, 0, 0]]
在元素上循环:
for (colname, rowname), value in list1:
查找列和行:
col = columns[colname]
row = rows[rowname]
并存储号码:
matrix[row][col] = value
就这些了。
好吧,差不多了。您的数据有问题,其中一个字符串是
'pear '
,而不是
'pear
'. 如果这是数据中的一个错误,你可以修复它。如果你的代码应该处理这个问题,你必须决定如何处理它。一个明显的选择是去掉字符串中多余的空白:
col = columns[colname.strip()]
row = rows[rowname.strip()]
如果你事先不知道所有的标签,并且需要以编程的方式找到它们怎么办?
您只需在主列表之前额外传递一次列表,就可以拉出所有唯一的行和列名称。例如:
rows, columns = {}, {}
for (colname, rowname), value in list1:
if rowname not in rows:
next_unused_index = len(rows) + 1
rows[rowname] = next_unused_index
if colname not in columns:
next_unused_index = len(columns) + 1
columns[colname] = next_unused_index
现在,要构建矩阵,您需要根据这两条指令构建它。如果您使用的是Python3.7,那么您可以依赖这样一个事实:dicts的顺序是正确的,但是不依赖它可能会更清楚。我们先建立一个空矩阵:
matrix = [[0 for _ in range(len(columns)+1)]
for _ in range(len(rows)+1)]
然后填写标题:
matrix[0][0] = '///'
for rowname, row in rows.items():
matrix[row][0] = rowname
for colname, column in columns.items():
matrix[0][column] = colname
然后可以运行与以前相同的代码来填充值。