为了账号安全,请及时绑定邮箱和手机立即绑定

在Python中将数据列表转换成矩阵(检查内部)

在Python中将数据列表转换成矩阵(检查内部)

红糖糍粑 2021-05-08 10:06:31
我正在编写将列表列表转换为矩阵的代码。此功能应可扩展到更大的列表,我的输入仅是为了使问题更易于解决。我仍然是初学者,所以我需要一点帮助=)-input:在示例输入中,list1是水果和颜色对的数据集:list1 = [[["apple", "red"], " 1 "],[["apple", "yellow"], " 1 "], [["apple", "green"], " 1 "]]list1 += [[["lemon", "red"], " 0 "], [["lemon", "yellow"], " 1 "], [["lemon", "green"], " 0 "]]list1 += [[["pear ", "red"], " 0 "], [["pear", "yellow"], " 0 "], [["pear", "green"], " 1 "]]-所需的输出:['', 'apple', 'lemon', 'pear']['red', ' 1 ', 0, 0]['yellow', 0, ' 1 ', 0]['green', 1, 0, ' 1 ']-我的输出['///', 'apple', 'lemon', 'pear']['red', ' 1 ', 0, 0]['yellow', 0, ' 1 ', 0]['green', 0, 0, ' 0 ']------我的尝试:-----# create empty matrixmatrix=[]for row in range(4):    new_row =[]    for col in  range(4):        new_row.append(0)   #if starting    all-0    matrix.append(new_row)    # add object names    names = ["///", "apple", "lemon", "pear"]    color = ["///", "red", "yellow", "green"]    color = color[::-1]    matrix[0] = names    for row in matrix:        row[0] = color.pop()    second_obj = 0    for row in range(4):        for col in range(4):            if list[row][0][0] == matrix[0][col]:                while list[row][0][1] != matrix[second_obj][0]:                    second_obj += 1                else:                    if matrix[row][row] != "///":                        matrix[row][row] = list[row][1]                     second_obj = 0
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

编写手动循环来搜索列表会使事情变得过于复杂。编写两个循环以搜索两个字符串列表,并尝试将它们混合在一起,同时还循环索引其他内容……这也就不足为奇了。


让我们废弃它,而使用一些字典:


columns = {'apple': 1, 'lemon': 2, 'pear': 3}

rows = {'red': 1, 'yellow': 2, 'green': 3}

现在,如果您想知道要放入哪个矩阵元素,则没有循环,只有两个字典查找:


>>> (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

现在,要构建矩阵,您需要根据这两个字典来构建。如果您使用的是python 3.7,则可以依靠dict顺序正确的事实,但不依赖于dict可能更清楚。让我们首先构建一个空矩阵:


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

…然后您可以运行与之前相同的代码来填写值。


查看完整回答
反对 回复 2021-05-11
  • 1 回答
  • 0 关注
  • 414 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号