如何分离这个Python列表?

时间:2011-12-20 00:54:04

标签: python list

如何在Python 2.6中将此列表分成几部分,我在3小时后完全感到困惑,需要帮助!

['X1', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X2', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X3', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)']

我需要这样的输出:

X1 P1 0 0 0
X1 P2 0 0 0
X1 P3 0 0 0

X2 P1 0 0 0
X2 P2 0 0 0
X2 P3 0 0 0

X3 P1 0 0 0
X3 P2 0 0 0
X3 P3 0 0 0

由于

4 个答案:

答案 0 :(得分:3)

    for i in xrange(0,12,4):
        for j in xrange(1,4):
            sub_list = list[i+j].strip(')').split('(')
            print list[i], sub_list[0], ' '.join(sub_list[1].split(','))
        print '\n'

会给你想要的输出。

答案 1 :(得分:1)

使用itertools.groupbytranslate的解决方案:

import itertools
import string

table = string.maketrans("(", " ")
lastX = None
for k, g in itertools.groupby(yourlist, lambda e: e[0] == 'X'):
    if k:
        lastX = next(g) 
        continue
    for p in g:
        print lastX, p.translate(table, ",)")
    print

对我来说这打印:

X1 P1 0 0 0
X1 P2 0 0 0
X1 P3 0 0 0

X2 P1 0 0 0
X2 P2 0 0 0
X2 P3 0 0 0

X3 P1 0 0 0
X3 P2 0 0 0
X3 P3 0 0 0

这是期望的结果。

答案 2 :(得分:0)

试试这个     导入重新

items = ['X1', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X2', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X3', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)']

regex = re.compile("(\w\d)\((.+)\)")

for i in range(0,len(items),4):
    x = items[i]
    for j in range(i+1,i+4):
        s = x
        r = regex.search(items[j])
        subheader = r.groups()[0]
        subitems = r.groups()[1].split(',')
        s = s + ' ' + subheader
        for si in subitems:
            s = s + ' ' + si
        print s
    print 

答案 3 :(得分:0)

这应该这样做:

data = ['X1', 'P1(0, 0, 0)',
              'P2(0, 0, 0)',
              'P3(0, 0, 0)',
        'X2', 'P1(0, 0, 0)',
              'P2(0, 0, 0)',
              'P3(0, 0, 0)',
        'X3', 'P1(0, 0, 0)',
              'P2(0, 0, 0)',
              'P3(0, 0, 0)']

which_x = None
for elem in data:
    if 'X' in elem:
        which_x = elem
        print
        continue
    elif '(' in elem:
        pvalue, paren, rest = elem.partition('(')
        vec = map(int, rest.replace(')', '').split(', '))
        print which_x, pvalue,
        print ' '.join([str(v) for v in vec])
    else:
        raise ValueError('Unknown pattern')