-1

I am trying to take 200 lines and convert each group of 10 into its own list.

1
Victorious Boom
834
7
0
7.00
1
0
1.00
1
2
Tier 1 Smurf
806
4
0
4.00
1
0
1.00
1
3
AllHailHypnoToad
754
4
0
4.00
1
0
1.00
1

which I want to look like:

1 Victorious Boom 834 7 0 7.00 1 0 1.00 1
2 Tier 1 Smurf 806 4 0 4.00 1 0 1.00 1
3 AllHailHypnoToad 754 4 0 4.00 1 0 1.00 1

Any help would be much appreciated

  • 2
    Possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – awesoon Jul 08 '16 at 05:25
  • Please show us what you have attempted so far, and demonstrate how the output does not give what you require. – SiHa Jul 08 '16 at 07:25

3 Answers3

1
full_list = [line.strip() for line in open("filename", 'r')] #read all lines into list
sublist = [full_list[i:i+10] for i in range(0, len(full_list), 10)]  #split them into sublist with 10 lines each
user3404344
  • 1,707
  • 15
  • 13
  • I was able to make this semi-work. I used an earlier list of that data, but it contains HTML table data from earlier in the scrape. What's the best way to remove the and from the list? `[[1, Victorious Boom, 834, 7, 0, 7.00, 1, 0, 1.00, 1], [2, Tier 1 Smurf, 806, 4, 0, 4.00, 1, 0, 1.00, 1]]` – E. Salisbury Jul 08 '16 at 16:47
  • I found a way around it by including `import re` `regex = '(.+?)'` `pattern = re.compile(regex)` then in my while loop adding: `table = re.findall(pattern, "list obj here")` `subtable = subtable = [table[i:i+10] for i in range(0, len(table), 10)]` Responds with: `[['1', 'Victorious Boom', '834', '7', '0', '7.00', '1', '0', '1.00', '1'], ['2', 'Tier 1 Smurf', '806', '4', '0', '4.00', '1', '0', '1.00', '1']` – E. Salisbury Jul 08 '16 at 17:40
0
count=0
fixed_list=[]
temp_list=[]
for line in open("some.txt").readlines():
    count+=1
    temp_list.append(line.strip())
    if (count%10)==0:
        fixed_list.append(temp_list)
        temp_list=[]
print fixed_list
spritecodej
  • 459
  • 1
  • 4
  • 13
0

Here is my answer. It takes a source.txt with the line by line type data and outputs the data in sets of 10 into the target.txt file. I hope this helps.

file  = open("source.txt", "r")
data = []
for line in file:
    data.append(line)
length = len(data)
file.close()

#output file
target = open("target.txt", "w")

#will become a line in the file
item = ""

if length % 10 == 0:
    for y in range(0, length, 10): 
        for x in range(0, 10):
            item += str(data[x + y].strip()) + " "
        target.write(item + "\n")
        item = ""   
else:
    print ("Bad data set. File "+ str(length) + " elements!")
Fabced
  • 63
  • 7