Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python dict1[d]=c只将列表2中的最后一项添加为字典中的值,我如何解决它?_Python - Fatal编程技术网

Python dict1[d]=c只将列表2中的最后一项添加为字典中的值,我如何解决它?

Python dict1[d]=c只将列表2中的最后一项添加为字典中的值,我如何解决它?,python,Python,当我输入“a,b,c,d” 输出是{'a':'d','b':'d'},我想要{'a':'c','b':'d'}问题在于循环逻辑: dict1 = {} list1 = [] list2 = [] x = input("Enter something: ").split(',') if len(x) % 2 == 1: b = input("please, add one more thing: ") x.append(b) for A in x[:len(x)//2]:

当我输入“a,b,c,d”
输出是{'a':'d','b':'d'},我想要{'a':'c','b':'d'}

问题在于循环逻辑:

dict1 = {}
list1 = []
list2 = []

x = input("Enter something: ").split(',')

if len(x) % 2 == 1:
    b = input("please, add one more thing: ")
    x.append(b)

for A in x[:len(x)//2]:
    list1.append(A)
for B in x[(len(x)//2):]:
    list2.append(B)
for d in list1:
    for c in list2:
        dict1[d] = c

print(dict1)
内部循环重复重写dict1[d];只获得最后一个元素。我认为您需要的是从两个列表中排序成对

for d in list1:
    for c in list2:
        dict1[d] = c
了解你想要实现的目标会有所帮助;这似乎是一种非常不舒服的建立目录的方式

没有邮政编码,自己通信:

for d, c in zip(list1, list2):
    dict1[d] = c
在这种情况下可以使用zip()函数

for i in range(len(list1)):
    dict1[list1[i]] = list2[i]

这里不需要初始化,只需使用
dict
zip
将列表切成两半即可

dict1 = {}
list1 = []
list2 = []

x = input("Enter something: ").split(',')

if len(x) % 2 == 1:
    b = input("please, add one more thing: ")
    x.append(b)

for A in x[:len(x)//2]:
    list1.append(A)
for B in x[(len(x)//2):]:
    list2.append(B)

for ele in zip(list1, list2):
    dict1[ele[0]] = ele[1]
print dict1

谢谢,但我还没学会拉拉链。还有别的办法吗?哦,那更好谢谢!我还没有学会Zip,我的讲师不会接受的。一个人已经回答了我的问题。谢谢
x = input("Enter something: ").split(',')

if len(x) % 2 == 1:
    b = input("please, add one more thing: ")
    x.append(b)

h = len(x)//2
dict1 = dict(zip(x[:h], x[h:]))