Python:尝试通过迭代器上的切片获取列表的三个元素

Python:尝试通过迭代器上的切片获取列表的三个元素,python,list,Python,List,我是python新手 我正在尝试从一个大列表创建另一个列表,一次只包含该列表中的3个元素 我正在尝试这个: my_list = ['test1,test2,test3','test4,test5,test6','test7,test8,test9','test10,test11,test12'] new_three = [] for i in my_list: item = my_list[int(i):3] new_three.append(item) # h

我是python新手

我正在尝试从一个大列表创建另一个列表,一次只包含该列表中的3个元素

我正在尝试这个:

my_list = ['test1,test2,test3','test4,test5,test6','test7,test8,test9','test10,test11,test12']
new_three = []
for i in my_list:    
    item = my_list[int(i):3]
    new_three.append(item)

    # here I'll write a file with these 3 elements. Next iteration I will write the next three ones, and so on...
我得到了这个错误:

item = my_list[int(i):3]
ValueError: invalid literal for int() with base 10: 'test1,test2,test3'
我还尝试:

from itertools import islice
for i in my_list:
    new_three.append(islice(my_list,int(i),3))
我也犯了同样的错误。我不知道我做错了什么

编辑:

在这里经过多次尝试和帮助后,我终于成功了

listrange = []
for i in range(len(li)/3 + 1):
    item = li[i*3:(i*3)+3]
    listrange.append(item)

这就是你的意思吗

my_list = ['test1,test2,test3','test4,test5,test6','test7,test8,test9','test10,test11,test12']
for item in my_list:
    print "this is one item from the list :", item    
    list_of_things = item.split(',')
    print "make a list with split on comma:", list_of_things
    # you can write list_of_things to disk here
    print "--------------------------------"
作为对注释的响应,若要生成一个全新的列表,并将逗号分隔的字符串转换为子列表,这就是列表理解:

new_list = [item.split(',') for item in my_list]
要将其从原始列表中分为三组,请参见PM 2Ring评论中链接的答案

我已根据您的具体情况进行了调整:

my_list = ['test1,test2,test3','test4,test5,test6','test7,test8,test9','test10,test11,test12']

for i in xrange(0, len(my_list), 3):
    # get the next three items from my_list
    my_list_segment = my_list[i:i+3]

    # here is an example of making a new list with those three
    new_list = [item.split(',') for item in my_list]
    print "three items from original list, with string split into sublist"
    print my_list_segment
    print "-------------------------------------------------------------"

    # here is a more practical use of the three items, if you are writing separate files for each three
    filename_this_segment = 'temp' # make up a filename, possibly using i/3+1 in the name
    with open(filename_this_segment, 'w') as f:
        for item in my_list_segment:
            list_of_things = item.split(',')
            for thing in list_of_things:
                # obviously you'll want to format the file somehow, but that's beyond the scope of this question
                f.write(thing)

预期的输出是什么?相关:当使用for循环时,python将迭代列表成员,而不是索引,错误消息证明了这一点。当你一次说列表中的3个元素时,你是指我的列表中的3个字符串吗?凯文说的。上面给出的
my_list
只包含4个元素。你可能会发现这里的答案很有用:也可以查看链接页面。#第一次迭代
['test1','test2','test3'],['test4','test5','test6'],['test7','test8','test9']
#第二次迭代
['test10','test11','test12'],[#nextt三人小组],[#下一组三人]
#第三组练习
[#下一组三人],#下一组三人],#下一组三人],
#等等,我想你希望这个问题在PM 2Ring的评论中链接,除了使用split(',')。更新。。。