Python 如何在字典中的列表值中附加值
我的输出>>{x':'4',y':'5',z':'6'} 我的预期出局了Python 如何在字典中的列表值中附加值,python,list,dictionary,Python,List,Dictionary,我的输出>>{x':'4',y':'5',z':'6'} 我的预期出局了 {'x':[1,4],'y':[2,5],'z':[3,6]}必须对列表使用te append内置方法 y = "1 2 3 ; 4 5 6;" m = [x.strip().split(" ") for x in y.split(";") if len(x.strip()) > 0] m >> [['1', '2', '3'], ['4', '5', '6']] result = {'x':[],'y'
{'x':[1,4],'y':[2,5],'z':[3,6]}
必须对列表使用te append内置方法
y = "1 2 3 ; 4 5 6;"
m = [x.strip().split(" ") for x in y.split(";") if len(x.strip()) > 0]
m
>> [['1', '2', '3'], ['4', '5', '6']]
result = {'x':[],'y':[], 'z':[]}
for i in m:
result['x'] = i[0]
result['y'] = i[1]
result['z'] = i[2]
result
您还可以使用zip方法删除for循环,如下所示:
for i in m:
result['x'].append(i[0])
result['y'].append(i[1])
result['z'].append(i[2])
y=“1 2 3;4 5 6;”
m=[x.strip().split(“”)表示x在y.split(“”)中的位置,如果len(x.strip())>0]
M
>> [['1', '2', '3'], ['4', '5', '6']]
结果={'x':[],'y':[],'z':[]}
对于我在m:
结果['x'].append(i[0])
结果['y'].追加(i[1])
结果['z'].append(i[2])
结果
您正在替换列表,而不是附加到列表中
y=“1 2 3;4 5 6;”
m=[x.strip().split(“”)表示x在y.split(“”)中的位置,如果len(x.strip())>0]
M
>> [['1', '2', '3'], ['4', '5', '6']]
结果={'x':[],'y':[],'z':[]}
对于我在m:
结果['x'].append(i[0])
结果['y'].追加(i[1])
结果['z'].append(i[2])
结果
由于您使用的字典包含每个值的列表,因此需要使用函数append
:
zipped_lists = list(zip(*[['1', '2', '3'], ['4', '5', '6']]))
result['x'] = list(zipped_lists[0])
result['y'] = list(zipped_lists[0])
result['z'] = list(zipped_lists[0])
输出:
y = "1 2 3 ; 4 5 6;"
m = [x.strip().split(" ") for x in y.split(";") if len(x.strip()) > 0]
result = {'x':[],'y':[], 'z':[]}
for i in range(len(m)):
result['x'].append(m[i][0])
result['y'].append(m[i][1])
result['z'].append(m[i][2])
print(result)
这是一种使用
dict
和zip
的方法
{'x': ['1', '4'], 'y': ['2', '5'], 'z': ['3', '6']}
输出:
d = [['1', '2', '3'], ['4', '5', '6']]
result = ['x','y', 'z']
print(dict(zip(result, zip(*d))))
# or
print({k: list(v) for k, v in zip(result, zip(*d))})
我将添加defaultdict方法:
{'x': ('1', '4'), 'y': ('2', '5'), 'z': ('3', '6')}
#
{'x': ['1', '4'], 'y': ['2', '5'], 'z': ['3', '6']}
输出:
m = [['1', '2', '3'], ['4', '5', '6']]
result_keys = ('x', 'y', 'z')
result = {}
for m1, m2, key in zip(*m, result_keys):
result[key] = [int(m1), int(m2)]
print(result)
m = [['1', '2', '3'], ['4', '5', '6']]
result_keys = ('x', 'y', 'z')
result = {}
for m1, m2, key in zip(*m, result_keys):
result[key] = [int(m1), int(m2)]
print(result)
{'x': [1, 4], 'y': [2, 5], 'z': [3, 6]}