python-3.x - 如何获取二维字符串列表并返回字典?每行的第一个元素是键
问题描述
获取字符串的二维列表(即列表列表)。它返回一个字典,其键是每行的第一个元素,并且每个这样的键都映射到由该行的其余元素组成的列表。
一直在为试图解决这个问题的极客寻找极客。我知道如何到达我想从中提取的第一个列表,但我不知道如何访问每个列表,然后将其作为值放入新字典中,其余字符串作为字典中的值。
def list2dict(list2d):
new_dict = {}
for i in range(list2d[0]):
for j in range(2):
new_dict.append[j] + ':' + list2d[j]
return new_dict
list2d is a 2d list of strings
Input:
1. Let x1 be the following list of lists:
[ [ 'aa', 'bb', 'cc', 'dd' ],
[ 'ee', 'ff', 'gg', 'hh', 'ii', 'jj' ],
[ 'kk', 'll', 'mm', 'nn' ] ]
Output:
Then list2dict(x1) returns the dictionary
{ 'aa' : [ 'bb', 'cc', 'dd' ],
'ee' : [ 'ff', 'gg', 'hh', 'ii', 'jj' ],
'kk' : [ 'll', 'mm', 'nn' ]
}
Input
2. Let x2 be the following list of lists:
[ [ 'aa', 'bb' ],
[ 'cc', 'dd' ],
[ 'ee', 'ff' ],
[ 'gg', 'hh' ],
[ 'kk', 'll' ] ]
Output
Then list2dict(x2) returns the dictionary
{ 'aa' : [ 'bb' ],
'cc' : [ 'dd' ],
'ee' : [ 'ff' ],
'gg' : [ 'hh' ],
'kk' : [ 'll' ]
}
解决方案
我想你正在寻找这样的东西...... 在线版
def list2dict(list2d):
new_dict = {}
for i in list2d:
key = i[0]
list = i[1:len(i)]
new_dict[key] = list
print(new_dict)
return new_dict
推荐阅读
- java - 最新稳定版本的黄瓜
- javascript - 如何在另一个文件中调用 JS 函数?
- javascript - 如何将具有泛型类型的方法发送到 RXJS bindCallback?
- python - 如何使用 numpy 更改二维数组元素
- python - 为特定行和列绘制 DataFrame Python
- sql-server - SQL CriteriaBuilder API 中的投射日期
- python - 如何在 django 中仅存储云图像 url?
- r - 比较不同数据帧的不同列和标志匹配
- r - 每次唯一字符串值在 r 中的其他列中具有 TRUE 值时,如何重新构造数据以计数/绘图?
- autodesk-forge - FORGE Viewer 长时间使用偶尔卡顿,无法加载模型