2011-12-20 58 views
-2

如何在Python 2.6中將這個列表分成幾塊,3小時後我完全困惑,需要幫助!如何區分這個Python列表?

['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 

感謝

回答

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' 

會給你所需的輸出。

+0

工作完美,非常容易定製它,謝謝。 – 2011-12-20 01:09:50

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 
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') 
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 

這是期望的結果。