如何将字符串的元素放在具有某种行为的列表中 [英] How can I put an element of a string in a list with a certain behaviour
本文介绍了如何将字符串的元素放在具有某种行为的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
list1 = ['A', 'B']
list2 = [[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]]
我需要我的输出:
[[(1, 1), (1, 2), (1, 3), (1, 4)],[(2, 1), (2, 2), (2, 3), (2, 4)]]
现在,如果我知道:
- 的sublist1 = 4
- sublist2 = 4的长度
那么我该怎么把这一切在一个字典中,如:
then how can I put all this in a dictionary like:
{'A':length of sublist1, 'B':length of sublist2}
推荐答案
使用split和groupby:
Using split and groupby:
>>> from itertools import groupby
>>> data = [map(int, (z for z in x.split(','))) for x in string1.split()]
>>> a, b = [list(j) for j in groupby(data, key=operator.itemgetter(0))]
>>> a
[[1, 1], [1, 2], [1, 3], [1, 4]]
>>> b
[[2, 1], [2, 2], [2, 3], [2, 4]]
然后你可以做:
>>> dict(zip(list1, (len(i) for i in (a,b))))
{'A': 4, 'B': 4}
这篇关于如何将字符串的元素放在具有某种行为的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文