2012-07-30 19 views
2
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} 
+0

看在'split()',列表解析,'len()'和'dict'构造函数中。 – 2012-07-30 17:19:31

+0

确定如何对字符串中的项目进行分组的规则究竟是什么?如果有12对而不是8对,是两个4或6中的3个?或者它是将它切成足够的块与list1一起使用? – 2012-07-30 17:19:59

+0

如果1,1或1,2的第一个元素是1,那么它应该保存在sublist1中,否则如果第一个元素2,1或2,2或2,3是2,那么它应该保存在sublist2中。 – smazon09 2012-07-30 17:23:21

回答

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)]) 
4

采用分体式和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

看起来你有你的数据位打减少到你想要的方式。就像下面的第一部分演示,然后你将不得不创建一个字典,然后在字典中查找值。以下是您的示例数据的代码。你应该建立在这个基础上。

>>> 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)]] 
+0

的问题中指定的方式完成,如果我得到如[[(1,1),(1,2),(1,3),(1,4))的输出, (2,1),(2,2),(2,3),(2,4)]]那么我应该如何分裂这个像你显示的那个? – smazon09 2012-07-30 17:53:08

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} 
相关问题