[英]Zip key value pairs in python
I need to change my output from number 1 = 0 to (1:0) or ('1':0). 我需要将输出从数字1 = 0更改为(1:0)或('1':0)。 I want to change to key value pair. 我想更改为键值对。 Below is the code I'm using. 下面是我正在使用的代码。
numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
print 'number ', number, ' = ', val
output: number 1 = 0
desired output is: ('1':0) or (1:0)
输出: number 1 = 0
所需输出为:( ('1':0) or (1:0)
numberlist = [1, 2, 3]
val_list = [4, 5, 6]
mydictionary = dict(zip(numberlist,val_list))
This will create a dictionary with numberlist
as the key and val_list
as the value. 这将创建一个字典,其中numberlist
为键, val_list
为值。
>>> mydictionary
{1: 4, 2: 5, 3: 6}
>>> mydictionary[1]
4
You can use a formatted print statement to achieve this: 您可以使用格式化的print语句来实现此目的:
numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
print "(%d:%d)" % (number, val, )
to print (1:0), or 打印(1:0),或
numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
print "('%d':%d)" % (number, val, )
to print ('1':0) 打印('1':0)
Personally, I'm a fan of the splat operator. 就个人而言,我是splat运营商的粉丝。
numberlist = [1, 3, 5]
val_list = [0, 2, 4]
for fmt in zip(numberlist, val_list):
print("('{}':{})".format(*fmt))
Keep in mind that each item in each list is an integer, but is being printed with quotes. 请记住,每个列表中的每个项目都是整数,但正在使用引号打印。 If you actually want to convert each to a string, you can do something like: 如果您确实想将每个转换为字符串,您可以执行以下操作:
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
Use the built in dict function after zip. zip后使用内置的dict函数。 This will give you a dictionary and then you can iterate over the dictionary to obtain a key value pair. 这将为您提供一个字典,然后您可以遍历字典以获取键值对。
numberlist = [1]
val_list = [0]
print dict(zip(numberlist, val_list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.