0

我有一个按列表的第二个值(组)排序的列表列表。我现在需要遍历这个以一次处理每个“组”。数据是[name, group, data1, data2, data3, data4]. 我不确定我是否需要一段时间或其他类型的循环,或者也许groupby但我从未使用过。任何帮助,将不胜感激。

for i in range (int(max_group)):
    x1 = []
    x2 = []
    x3 = []
    x4 = []
    if data[i][1] == i+1:
        x1.append(data[2])
        x2.append(data[3])
        x3.append(data[4])
        x4.append(data[5])
        print x1
        print 'next' # these are just to test where we're at

所有 x 都应该包含所有第 1 组信息的所有第 3-5 列数据(在名称和组号之后)。然后我可以使用第 1 组信息并转到第 2 组。

4

2 回答 2

1
for i in sorted(set(group[1] for group in data)):
    x1, x2, x3, x4 = zip(*(group[2:] for group in data if group[1] == i))

注意:这个解决方案效率很低,我会在一分钟内带来一个更高效的解决方案!

groups = {}
for d in data:
    try:
        groups[d[1]].append(d[2:])
    except AttributeError:
        groups[d[1]] = d[2:]

for i in sorted(j for j in groups):
    x1, x2, x3, x4 = zip(*groups[i])

这只是稍微不那么难看,但应该可以工作

于 2012-12-05T05:01:05.457 回答
0

假设列表中的列表是

mylist = [[name],[add],[data1],[data2]]

要遍历列表中的每个列表,您应该尝试以下代码:

for each_list in mylist:
    if isinstance(each_list,list):
         #do something with that list inside list

抱歉,如果此答案与您的问题不符。

于 2012-12-05T05:05:39.793 回答