如何从列表在python中创建多维数组?
我有一个包含如下元素的列表如何从列表在python中创建多维数组?,python,Python,我有一个包含如下元素的列表 list1 = [['Test Name', 'Results', 'Units', 'Bio. Ref. Interval'], ['Cholesterol, Total', '243.00', 'mg/dL', '<200.00'], ['Triglycerides', '365.00', 'mg/dL', '<150.00'], ['HDL Cholesterol', '48.56', 'm
list1 = [['Test Name', 'Results', 'Units', 'Bio. Ref. Interval'],
['Cholesterol, Total', '243.00', 'mg/dL', '<200.00'],
['Triglycerides', '365.00', 'mg/dL', '<150.00'],
['HDL Cholesterol', '48.56', 'mg/dL', '>50.00'],
['LDL Cholesterol, Calculated', '121.44', 'mg/dL', '<100.00'],
['VLDL Cholesterol, Calculated *', '73.00', 'mg/dL', '<30.00'],
['Non-HDL Cholesterol', '194', 'mg/dL', '<130']]
我是python的新手。请提供帮助。您需要字典的唯一键,以便执行以下操作:
dict1 = {f'Test {j}': {list1[0][i]: list1[j][i] for i in range(4)} for j in range(1, len(list1))}
将具有以下输出
{'Test 1': {'Test Name': 'Cholesterol, Total', 'Results': '243.00', 'Units': 'mg/dL', 'Bio. Ref. Interval': '<200.00'},
'Test 2': {'Test Name': 'Triglycerides', 'Results': '365.00', 'Units': 'mg/dL', 'Bio. Ref. Interval': '<150.00'},
'Test 3': {'Test Name': 'HDL Cholesterol', 'Results': '48.56', 'Units': 'mg/dL', 'Bio. Ref. Interval': '>50.00'},
'Test 4': {'Test Name': 'LDL Cholesterol, Calculated', 'Results': '121.44', 'Units': 'mg/dL', 'Bio. Ref. Interval': '<100.00'},
'Test 5': {'Test Name': 'VLDL Cholesterol, Calculated *', 'Results': '73.00', 'Units': 'mg/dL', 'Bio. Ref. Interval': '<30.00'},
'Test 6': {'Test Name': 'Non-HDL Cholesterol', 'Results': '194', 'Units': 'mg/dL', 'Bio. Ref. Interval': '<130'}}
将列表转换成词典有几种方法,一种是dict理解法,另一种是zip方法 参考此->输出将是字典列表。不是字典的字典,因为我们这里需要钥匙 您需要知道如何迭代列表和列表上的切片操作。 您应该知道zip函数是如何工作的。 以及列表的附加方法。 代码:
请求的输出不能是字典,因为没有提到键,而只是字典列表
my_list_of_dictionaries = [{k:i[list1[0].index(k)] for k in list1[0]} for i in list1[1:]]
是否希望密钥包含在一个完整的字符串中:Testname:“非HDL胆固醇”?您的预期输出不是有效的。非常感谢。这正是我想要的:
list1 = [
['Test Name', 'Results', 'Units', 'Bio. Ref. Interval'],
['Cholesterol, Total', '243.00', 'mg/dL', '<200.00'],
['Triglycerides', '365.00', 'mg/dL', '<150.00'],
['HDL Cholesterol', '48.56', 'mg/dL', '>50.00'],
['LDL Cholesterol, Calculated', '121.44', 'mg/dL', '<100.00'],
['VLDL Cholesterol, Calculated *', '73.00', 'mg/dL', '<30.00'],
['Non-HDL Cholesterol', '194', 'mg/dL', '<130']
]
# Output will be list of dictionary. Not dictionary of dictionary because we require key here.
keys = list1[0]
output_list = []
for item in list1[1:]:
_tmp = {}
for key, value in zip(keys, item):
_tmp[key] = value
output_list.append(_tmp)
print("output_list:", output_list)
output_list = [dict(zip(keys, item)) for item in list1[1:]]
print("output_list:", output_list)
my_list_of_dictionaries = [{k:i[list1[0].index(k)] for k in list1[0]} for i in list1[1:]]