如何将字符串元素放在具有特定行为的列表中

时间:2012-07-30 17:13:32

标签: python list dictionary

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

然后我怎么能把所有这些都放在一个字典中:

{'A':length of sublist1, 'B':length of sublist2}

4 个答案:

答案 0 :(得分:4)

使用split和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}

答案 1 :(得分:1)

您可以按如下方式获取列表清单:

from collections import defaultdict

data = defaultdict(list)
for val in string1.split():
    v1, v2 = val.split(',')
    data[v1].append(v2)
result = [[(int(key), int(v)) for v in values] for key, values in data.items()]

要获取字典,您可以这样做:

d = dict(zip(list1, result))

这会为您提供一个包含list1元素作为键的列表。为了得到你可以做的长度:

d = dict([(key, len(ls)) for key, ls in zip(list1, result)])

答案 2 :(得分:1)

看起来你必须稍微使用你的数据来减少你想要它的方式。像下面的第一部分演示,然后你将不得不创建一个字典,然后在字典中查找值。以下是您的示例数据的代码。你应该建立起来。

>>> string1 = '1,1 1,2 1,3 1,4 2,1 2,2 2,3 2,4'
>>> list1 = string1.split(',')
>>> list2 = [tuple(map(int, a.split(','))) for a in list1]
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]

>>> temp_dict = {}
>>> for each in list2:
...     a = each[0]
...     if a in temp_dict:
...             temp_dict[a].append(each)
...     else:
...             temp_dict[a] = [each]
... 
>>> temp_dict.values()
[[(1, 1), (1, 2), (1, 3), (1, 4)], [(2, 1), (2, 2), (2, 3), (2, 4)]]

答案 3 :(得分:0)

获取元组列表,并根据每个元组中的第一个数字将其拆分为单独的列表。在同一步骤中,使用list1中的相应密钥将过滤后的列表添加到字典中。由于list2中的双括号(下方复制),实际数据位于list2[0]

//note the double brackets, data is in list2[0], not list2
list2 = [[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]]

d = dict()

for i in range (0, len(list1)):
     d[list1[i]] = [x for x in list2[0] if x[0] == i+1]
     //on the first run though, list[i] will be 'A' and will be set to [(1, 1), (1, 2), (1, 3), (1, 4)]
     //on the 2nd run though, list[i] will be 'B' and will be set to [(2, 1), (2, 2), (2, 3), (2, 4)]

打印d显示格式化数据

print(d)
//prints {'A': [(1, 1), (1, 2), (1, 3), (1, 4)], 'B': [(2, 1), (2, 2), (2, 3), (2, 4)]}


编辑:我误读了这个问题(我以为你想要字典中的实际数据,而不仅仅是长度)。要获取列表的长度而不是内容,只需将第二个列表理解包装在len()

len([x for x in list2[0] if x[0] == i+1])

更改后,d将包含长度,而不是数据:

print(d) //{'A': 4, 'B': 4}