简体   繁体   English

将字符串列表中的字符映射到字典中,索引为键

[英]Map characters from list of strings into dictionary with index as key

I'm asking to put a list of strings into a dictionary, such that the indices of the characters are the keys and the values are the combined characters. 我要求将字符串列表放入字典中,以便字符的索引是键,值是组合字符。
I'm trying to get this as terse as I can. 我正试图尽可能简洁。

My code: 我的代码:

a = ['apple','pear']
b = map(lambda x:dict(enumerate(x)),a)
print b

Output: 输出:

[{0: 'a', 1: 'p', 2: 'p', 3: 'l', 4: 'e'}, {0: 'p', 1: 'e', 2: 'a', 3: 'r'}]

Desired output: 期望的输出:

{0:'ap',1:'pe',2:'pa',3:'lr',4:'e'}

you want zip 你想要拉链

dict(enumerate(zip(*a)))

or maybe izip_longest 或者也许是izip_longest

dict(enumerate(itertools.izip_longest(*a,fillvalue="")))

if you really need to you can join the letters easy enough 如果你真的需要,你可以很容易地加入这些信件

{k:"".join(v) for k,v in result.items()}

You can use itertools.zip_longest (in python 2 itertools.izip_longest ) within a dict comprehension : 你可以在dict理解中使用itertools.zip_longest (在python 2 itertools.izip_longest ):

>>> from itertools import zip_longest
>>> 
>>> {i:''.join(j) for i,j in enumerate(zip_longest(*a,fillvalue=''))}
{0: 'ap', 1: 'pe', 2: 'pa', 3: 'lr', 4: 'e'}

similar solution 类似解决方案

{i: x+y for i, (x,y) in enumerate(zip_longest(*a,fillvalue=''))}

{0: 'ap', 1: 'pe', 2: 'pa', 3: 'lr', 4: 'e'}

Do you know if I can do this without the itertools import , yes map will work to catch the shorter string as you are using python2: 你知道我是否可以在没有itertools导入的情况下做到这一点 ,是的map会在你使用python2时捕获更短的字符串:

a = ['apple','pear']
b = {i: a + b if b else a  for i, (a, b) in enumerate(map(None,*a))}

print(b)
{0: 'ap', 1: 'pe', 2: 'pa', 3: 'lr', 4: 'e'}

To work for either a or b being different lengths we need a little more logic: 要为a或b工作不同的长度,我们需要更多的逻辑:

b = {i: a if not b else b if not a else a + b for i,(a, b) in enumerate(map(None, *a))}

map(None,*a) will behave somewhat like zip_longest , None will be used as a fillvalue for the shorter string. map(None,*a)行为有点像zip_longest ,None将用作较短字符串的fillvalue。 We just check if a or b is None and do the appropriate thing based on the result. 我们只检查a或b是否为None,并根据结果做适当的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM