我怎样才能用两个元组来生成字典? [英] How can I take two tuples to produce a dictionary?

查看:73
本文介绍了我怎样才能用两个元组来生成字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个想法是写一个Interator,或者做一些列表理解.但是,就像我在python中编写的每5-10行方法一样,通常可以有人将我指向标准库中的调用以完成相同的操作.

My first thought is to write an interator, or maybe do some list comprehension. But, like every 5-10 line method I write in python, someone can usually point me to a call in the standard library to accomplish the same.

如何从两个元组 x y 转到字典 z ?

How can I go from two tuples, x and y to a dictionary z?

x = ( 1, 2, 3 )
y = ( 'a', 'b', 'c')

z = { }
for index, value in enumerate(y):
    z[value] = x[index]

print z

# { 'a':1, 'b':2, 'c':3 }

推荐答案

Tuples是 iterables .您可以使用 zip 将两个或多个可迭代对象合并为两个或多个元素的元组.

Tuples are iterables. You can use zip to merge two or more iterables into tuples of two or more elements.

字典可以由2个元组的迭代组成,所以:

A dictionary can be constructed out of an iterable of 2-tuples, so:

#          v values
dict(zip(y,x))
#        ^ keys

这将生成:

>>> dict(zip(y,x))
{'c': 3, 'a': 1, 'b': 2}

请注意,如果两个可迭代对象的长度不同,则从其中一个元组之一被用尽时起, zip 就会停止.

Note that if the two iterables have a different length, then zip will stop from the moment one of the tuples is exhausted.

您可以- @Wondercricket 说-使用 izip_longest (或 zip_longest )和 fillvalue :一个可迭代项用尽时使用的值:

You can - as @Wondercricket says - use izip_longest (or zip_longest in python-3.x) with a fillvalue: a value that is used when one of the iterables is exhausted:

from itertools import izip_longest

dict(izip_longest(y,x,fillvalue=''))

因此,如果可迭代的键首先被用尽,则所有剩余的值都将被映射到此处的空字符串上(因此将仅存储最后一个值).如果先将iterable值用尽,则所有其余键都将被映射到空字符串上.

So if the key iterable gets exhausted first, all the remaining values will be mapped on the empty string here (so only the last one will be stored). If the value iterable is exhausted first, all remaining keys will here be mapped on the empty string.

这篇关于我怎样才能用两个元组来生成字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆