我创建了一个名为">father_dict'"的字典,其关键字">关键字"分别为1、2和3,并且我为每个关键字值都关联了一个列表。
# ValueList Key
input_data = [[ 1, 'Col', 1],
[ 2, 'Col', 1],
[ 3, 'Col', 1],
[ 4, 'Col', 1],
[ 5, 'Col', 2],
[ 6, 'Col', 2],
[ 7, 'Col', 2],
[ 8, 'Col', 2],
[ 9, 'Col', 3],
[10, 'Col', 3],
[11, 'Col', 3],
[12, 'Col', 3],
[13, 'Row', 1],
[14, 'Row', 1],
[15, 'Row', 1],
[16, 'Row', 2],
[17, 'Row', 2],
[18, 'Row', 2],
[19, 'Row', 3],
[20, 'Row', 3],
[21, 'Row', 3]]
common_character = []
father_dict = {}
for i in range(len(input_data)):
if input_data[i][1] == 'Col':
common_character.append(input_data[i][2])
print(common_character)
flat_list = list(set(common_character))
print(flat_list)
for j in flat_list:
father_dict[j] = []
print(father_dict)
for i in range(len(input_data)):
if input_data[i][1] == 'Col':
key = input_data[i][2]
father_dict[key].append(input_data[i][0])
print(father_dict)
从那里我寻求创建两个字典:
具有相同关键字但与列表关联的第一个字典,在该列表中只找到'father_dict'列表的第一个和最后一个值。
我正在寻找的打印在屏幕上的示例:
{1: [1, 4], 2: [5, 8], 3: [9, 12]}
同样,使用相同的键创建第二个字典,但这些键与一个列表关联,在该列表中只能找到'father_dict'列表中间的值。
我正在寻找的打印在屏幕上的示例:
{1: [2, 3], 2: [6, 7], 3: [10, 11]}
这个过程是如何完成的?非常感谢。
对不起,我的英语不是我的母语
使用字典理解和切片,您可以执行以下操作:
# first and values
result1={
k:[v[0],v[-1]] for k,v in father_dict.items()
}
# middle values
result2={
k:[v[1:-1]] for k,v in father_dict.items()
}
dicts 2和2a:
#{ Key: [ dict[key][value at first position], dict[key][value at last position] ] } #do for each entry in source dict
d2a = {i:[ father_dict[i][0],father_dict[i][-1] ]
for i in father_dict
}
#{ Key: dict[key][positions 1 to just before last position] } #for each entry in source dict
d2b = {i: father_dict[i][1:-1]
for i in father_dict
}