如何将列表元素拆分为Python列表?

时间:2016-10-31 22:02:09

标签: python list for-loop typeerror

我的示例数据如下:

list1 = ['AAAABBBBCCCC','DDDDEEEEFFFF','GGGGHHHHIIII','JJJJKKKKLLLL']

  • 制作一个list1b,使每个元素分成四个

list1b = [['AAAA','BBBB','CCCC'],['DDDD','EEEE','FFFF'],['GGGG','HHHH','IIII'],['JJJJ','KKKK','LLLL']]

我试图为任何长度的元素编写一个通用代码:

list1a =[]
list1b =[]

for sublist in list1:
    n = 4
    quad = [input[i:i+n] for i in range(0, len(sublist[0]), n)] 
    list1a.append(quadruplets)
    quad =[] #Setting it back to empty list
    list1b.append(list1a)

print list1b

#Error Message: 
 quad = [input[i:i+n] for i in range(0, len(sublist[0]), n)] 
 TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

任何人都可以认识到我可能出错的地方以及我如何纠正它?有没有更简单的方法来做同样的事情?

3 个答案:

答案 0 :(得分:1)

如果您想按同一个字符分组,可以使用groupby执行此操作:

>>> from itertools import groupby
>>> list1 = ['AAAABBBBCCCC','DDDDEEEEFFFF','GGGGHHHHIIII','JJJJKKKKLLLL']
>>> [[''.join(g) for k,g in groupby(sl)] for sl in list1]
[['AAAA', 'BBBB', 'CCCC'], ['DDDD', 'EEEE', 'FFFF'], ['GGGG', 'HHHH', 'IIII'], ['JJJJ', 'KKKK', 'LLLL']]

如果按长度与字符进行分区,则可以执行以下操作:

>>> n=4
>>> [[s[i:i+n] for i in range(0, len(s), n)] for s in list1]
[['AAAA', 'BBBB', 'CCCC'], ['DDDD', 'EEEE', 'FFFF'], ['GGGG', 'HHHH', 'IIII'], ['JJJJ', 'KKKK', 'LLLL']]

答案 1 :(得分:0)

您的代码中只有一个错误的变量名:input应为sublistquaruplets错过d,而sublist[0]应为{ {1}}:

sublist

然后,您不需要中间列表,它只会将输出中的相同列表相乘。因此quadruplets = [sublist[i:i+n] for i in range(0, len(sublist), n)] 可以是list1a.append而忘记其余部分。 list1b.append没有理由陷入循环,所以你可以将其移出:

n = 4

一旦你拥有了它,你可以使它成为一个列表理解:

list1 = ['AAAABBBBCCCC','DDDDEEEEFFFF','GGGGHHHHIIII','JJJJKKKKLLL']
list1b =[]
n = 4

for sublist in list1:
    quadruplets = [sublist[i:i+n] for i in range(0, len(sublist), n)] 
    list1b.append(quadruplets)

print (list1b)

答案 2 :(得分:0)

如果在list1b之前先生成list2,可能会更容易。

list1 = ['AAAABBBBCCCC','DDDDEEEEFFFF','GGGGHHHHIIII','JJJJKKKKLLLL']

list1b = []
list2 = []

n = 4

for i in range(0, len(list1[0]), n):
    list2.append([x[i:i+n] for x in list1])

for i in range(len(list2[0])):
    list1b.append([x[i] for x in list2])

结果

list1b = [['AAAA', 'BBBB', 'CCCC'],
          ['DDDD', 'EEEE', 'FFFF'],
          ['GGGG', 'HHHH', 'IIII'],
          ['JJJJ', 'KKKK', 'LLLL']]

list2 = [['AAAA', 'DDDD', 'GGGG', 'JJJJ'], 
         ['BBBB', 'EEEE', 'HHHH', 'KKKK'], 
         ['CCCC', 'FFFF', 'IIII', 'LLLL']]