我有一个列表列表,按列表的第二个值(组)排序。我现在需要遍历它,以便一次处理每个“组”。数据是[name, group, data1, data2, data3, data4].的,我不确定我是需要while循环还是其他循环,或者是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。
发布于 2012-12-05 13:01:05
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-05 13:05:40
假设列表中的列表是
mylist = [[name],[add],[data1],[data2]]要遍历list中的每个列表,您应该尝试以下代码:
for each_list in mylist:
if isinstance(each_list,list):
#do something with that list inside list如果此答案与您的问题不匹配,很抱歉。
https://stackoverflow.com/questions/13716515
复制相似问题