python中的Zip键值对

时间:2016-03-10 16:25:03

标签: python

我需要将输出从数字1 = 0更改为(1:0)或(' 1':0)。我想更改为键值对。以下是我正在使用的代码。

numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
    print 'number ', number, ' = ', val

输出:number 1 = 0 期望的输出是:('1':0) or (1:0)

4 个答案:

答案 0 :(得分:2)

您可以使用格式化的print语句来实现此目的:

numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
    print "(%d:%d)" % (number, val, )

打印(1:0)或

numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
    print "('%d':%d)" % (number, val, )

打印(' 1':0)

答案 1 :(得分:2)

numberlist = [1, 2, 3]
val_list = [4, 5, 6]

mydictionary = dict(zip(numberlist,val_list))

这将创建一个字典,其中numberlist为关键字,val_list为值。

>>> mydictionary
{1: 4, 2: 5, 3: 6}
>>> mydictionary[1]
4

答案 2 :(得分:0)

就个人而言,我是splat运营商的粉丝。

numberlist = [1, 3, 5]
val_list = [0, 2, 4]
for fmt in zip(numberlist, val_list):
    print("('{}':{})".format(*fmt))

请记住,每个列表中的每个项目都是整数,但正在使用引号打印。如果您确实想将每个转换为字符串,则可以执行以下操作:

newList = zip(map(str, numberlist), val_list) # List of tuples
# or, if you want a dict:
newDict = dict(newList) # dict where each key is in numberlist and values are in val_list

答案 3 :(得分:0)

使用zip后的内置dict函数。这将为您提供一个字典,然后您可以遍历字典以获取键值对。

numberlist = [1]
val_list = [0]    
print dict(zip(numberlist, val_list))