Python 使用列表中的特定项创建字典
我正试图创建一个只使用列表中特定值的字典。以下是我目前的代码:Python 使用列表中的特定项创建字典,python,list,dictionary,Python,List,Dictionary,我正试图创建一个只使用列表中特定值的字典。以下是我目前的代码: my_dict = {1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 3, 4], 5: [1, 3, 4, 5], 6: [1, 3, 4, 5, 6]} my_list = ([1, 1, 0], [1, 2, 100], [1, 3, 150], [1, 4, 150], [1, 5, 10], [1, 6, 20]) new_list = [] o_d = 0 # making the AON
my_dict = {1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 3, 4], 5: [1, 3, 4, 5], 6: [1, 3, 4, 5, 6]}
my_list = ([1, 1, 0], [1, 2, 100], [1, 3, 150], [1, 4, 150], [1, 5, 10], [1, 6, 20])
new_list = []
o_d = 0
# making the AON list
new_dict = {}
for i in my_list:
if i[0] and i[1] in my_dict:
new_list.append(my_list[o_d][1])
new_list.append(my_list[o_d][2])
for key in my_dict:
new_dict[key] = my_list[o_d][2]
o_d += 1
else:
o_d += 1
print(o_d)
print(new_list)
print(new_dict)
我得到的结果是:
6
new_list [1, 0, 2, 100, 3, 150, 4, 150, 5, 10, 6, 20]
new_dict {1: 20, 2: 20, 3: 20, 4: 20, 5: 20, 6: 20}
问题是,在o_d循环遍历整个列表之后,我只添加了我的_列表中第6项的第三个值。如何添加每个o_d迭代的第三个值
以下是我的预期输出:
{1: 0, 2: 100, 3: 150, 4: 150, 5: 10, 6: 20}
这是因为您在outter for循环的每次迭代中都重写了new_dict的所有元素。您需要去掉内部for循环,只重写适当的新dict值或use.append(my_list[o_d][2]),这取决于您试图在输出中获取的内容 另外,您是否知道“if i[0]和i[1]在我的字典中:”检查i[0]是否不是空对象(例如0、[]、{}等)和i[1]在我的字典中,而不是i[0]和i[1]都在我的字典中?只要在if和else语句中运行“o_d+=1”部分,就可以将其移出if-else语句。我解决了它 代码如下:
my_dict = {1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 3, 4], 5: [1, 3, 4, 5], 6: [1, 3, 4, 5, 6]}
my_list = ([1, 1, 0], [1, 2, 100], [1, 3, 150], [1, 4, 150], [1, 5, 10], [1, 6, 20])
new_list = []
o_d = 0
# making the AON list
new_dict = {}
for i in my_list:
new_dict[o_d + 1] = my_list[o_d][2]
if i[0] and i[1] in my_dict:
new_list.append(my_list[o_d][1])
new_list.append(my_list[o_d][2])
o_d += 1
print(o_d)
print ("new_list", new_list)
print("new_dict", new_dict)
以下是输出:
6
new_list [1, 0, 2, 100, 3, 150, 4, 150, 5, 10, 6, 20]
new_dict {1: 0, 2: 100, 3: 150, 4: 150, 5: 10, 6: 20}
请发布预期的输出。谢谢您的建议,输出已完成。