如何在python中的某些点将列表拆分为较小的列表?

时间:2014-10-13 22:06:30

标签: python list

我有一系列不同的东西,我想知道每次点击新名称时如何分割它?

所以我想拥有一个如下所示的列表:

list = [corn, 14, 2, 500, broccoli, 2, 10, 1400, potato, 2, 14, 7]

它将创建3个列表:

list1 = [corn, 14, 2, 500]

list2 = [broccoli, 2, 10, 1400]

list3 = [potato, 2, 14, 7]

我猜这将是一个循环线,重复一个新的列表,直到它遇到一个非整数,但我真的不知道它将如何设置。

5 个答案:

答案 0 :(得分:2)

尝试这一点,假设新名称每四个元素出现在样本输入中:

lst = ['corn', 14, 2, 500, 'broccoli', 2, 10, 1400, 'potato', 2, 14, 7]
[lst[i:i+4] for i in xrange(0, len(lst), 4)]
=> [['corn', 14, 2, 500], ['broccoli', 2, 10, 1400], ['potato', 2, 14, 7]]

以上将返回一个子列表列表,每四个元素拆分一次。如果您确定输入列表中恰好有12个元素,则可以直接分配生成的子列表:

lst1, lst2, lst3 = [lst[i:i+4] for i in xrange(0, len(lst), 4)]

现在每个变量都包含预期的结果:

lst1
=> ['corn', 14, 2, 500]
lst2
=> ['broccoli', 2, 10, 1400]
lst3
=> ['potato', 2, 14, 7]

答案 1 :(得分:2)

检查String是否为数字(如果您要准确使用该代码,请不要忘记包含引号),请查看str.isdigit()

>>> 'corn'.isdigit()
False
>>> '123'.isdigit()
True

答案 2 :(得分:1)

这可能不是最漂亮的解决方案,但它能够在分隔符大小发生变化时做出响应(比如你想跟踪玉米和西兰花之间的另一个数字),并且如果你想要它也可以让它超过一组三个列表。 / p>

lst = ["corn", 14, 2, 500, "broccoli", 2, 10, 1400, "potato", 2, 14, 7]
string_indices = [index for (index, value) in enumerate(lst) 
                  if isinstance(value, str)]

# We want to include the last group as well
string_indices.append(len(lst))

sublists = [lst[string_indices[x]:string_indices[x+1]] 
            for x in xrange(len(string_indices) - 1)]

lst1, lst2, lst3 = sublists

最后,sublists等于:

[['corn', 14, 2, 500], ['broccoli', 2, 10, 1400], ['potato', 2, 14, 7]]                                                                                  

...并将其解压缩到如上所示的三个列表中。

答案 3 :(得分:1)

这很可怕但是会为你完成工作。


l = ["corn", 14, 2, 500, "broccoli", 2, 10, 1400, "potato", 2, 14, 7, 5, 6, 7, "carrot"]
out = []
for i in xrange(0, len(l)):
    if isinstance(l[i], str):
        tmp = []
        tmp.append(l[i])
        i += 1
        while (i < len(l)) and isinstance(l[i], int) :
            tmp.append(l[i])
            i += 1
        out.append(tmp)
In [41]: out
Out[41]:
[['corn', 14, 2, 500],
 ['broccoli', 2, 10, 1400],
 ['potato', 2, 14, 7, 5, 6, 7],
 ['carrot']]

答案 4 :(得分:1)

您发布的单行代码中存在两个问题

  1. 您可能希望使用字符串而不是通用对象 在您的列表中

  2. list是一个python函数,用于根据序列创建列表 一个可迭代的,值得让它自己,所以我们命名你的列表 a_list

  3. 以下内容基于一个假设,即您希望在每个字符串上拆分并仅在字符串

    上拆分
    a_list = ['corn', 14, 2, 500, 'broccoli', 2, 10, 1400, 'potato', 2, 14, 7]
    # initialize an empty list (I can do it in other ways, but I want
    # to show you an use of the `list` builtin function) and a counter `n`
    
    list_of_sublists = list() # the function 'list' is called with no arguments
    n = 0
    
    # iterate for the index and the corresponding element of the list
    for i, elt in enumerate(a_list):
        # when we reach the second string in the list we append the sublist
        # from the previous beginning `n=0`, do you remember? up to the current
        # index, that in python is _excluded_ from the sublist, and finally we
        # update the index for the start of the next sublist
        # NOTA BENE the SECOND string triggers the saving of the FIRST sublist
        if i and type(elt) == str:
            list_of_sublists.append(a_list[n:i])
            n = i
        # and of course the code above is triggered for the third, the ...,
        # the last string in the list
    
    # but when we reach the end of the loop, having found that there are no
    # further strings past the last one ;-) we have still the last sublist,
    # the one that starts with the last string, that waits for being appended
    # so here we do this last append
    
    list_of_sublists.append(a_list[n:])
    
    print list_of_sublists
    

    有人会反对测试type(elt) == str对于从str子类化的对象会失败,或者像str一样嘎嘎叫,但我认为你已经考虑过了'nuff的东西......