【问题标题】:How to create function to convert dictionary to a matrix without numpy or any similar package如何在没有 numpy 或任何类似包的情况下创建将字典转换为矩阵的函数
【发布时间】:2019-01-22 09:39:45
【问题描述】:

给你一个字典,它是数字和特征的映射。创建一个函数以将字典转换为没有 numpy 或任何类似包的矩阵。只需使用基本的 python 操作。 输入字典:

{
11:['a','b','c']
22:['c','d','e'] }

输出必须是这样的:

[ ['tag','a','b','c','d','e']
  [11,1,1,1,0,0] 
  [22,0,0,1,1,1] 
]

我试过了,但是帮不上忙

【问题讨论】:

  • 特征总是按顺序排列的吗?
  • 你能告诉我们你的尝试吗?
  • 听起来像学校测验。到目前为止,您尝试过什么?
  • 是的,功能总是按顺序排列
  • “香草”python 中没有矩阵类型。你的意思是lists

标签: python function dictionary matrix converter


【解决方案1】:

下次请不要忘记在cmets中添加每个人都要求你做的事情:)

d = {
    11:['a','b','c'],
    22:['c','d','e']
    }

all_val =  ['tag']
# using list comprehension
  # for v in d.values() <-- outer loop
    # for _ in v <-- inner loop
# set because idk whether each key have unique set of values 

for char in sorted(set([ _ for v in d.values() for _ in v] )):
    all_val.append(char)

output_2d = []
output_2d.append(all_val)

for k,v in d.items():
    output_2d.append([k])
    for tag in all_val[1:]:
        if tag in v:
            output_2d[-1].append(1)
        else:
            output_2d[-1].append(0)


print(output_2d)

[['tag', 'a', 'b', 'c', 'd', 'e'], [11, 1, 1, 1, 0, 0], [22, 0, 0 , 1, 1, 1]]

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    相关资源
    最近更新 更多