2016-07-08 15 views
-2

我試圖把200行轉換成10個自己的列表。使用Python將特定行轉換爲列表

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 
我想看看

像:

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 

任何幫助,將不勝感激

+2

的可能的複製[你怎麼分割成列表在Python均勻大小的塊?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into - 大小不一的塊 - 蟒蛇) – soon

+0

請告訴我們你到目前爲止所做的嘗試,並演示輸出如何不能滿足你的需求。 – SiHa

回答

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 
+0

我能夠做這個半工作。我使用了一個較早的數據列表,但它包含了早期在scrape中的HTML表格數據。從列表中刪除​​和的最佳方法是什麼? '[[​​1,​​勝利臂架,​​834,​​7,​​0,​​7.00,​​1,​​0,​​1.00,​​1],[​​2 ,​​Tier 1 Smurf,​​806,​​4,​​0,​​4.00,​​1,​​0,​​1.00,​​1]]' –

+0

我發現了一種方法圍繞它通過包括 '進口re' '正則表達式='​​(。 +)「'' 模式= re.compile(正則表達式)' 然後在我while循環加: '表= re.findall(模式 「列表OBJ這裏」)'' 子表=子表= [表格[我:我+10]我在範圍內(0,len(表格), 10)]' 迴應: '[['1','勝利熱潮','834','7','0','7.00','1','0','1.00',' '1'],['2','Tier 1 Smurf','806','4','0','4.00','1','0','1.00','1']' –

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 
0

這裏就是我的回答。 它採用逐行類型數據的source.txt格式,並將10組數據輸出到target.txt文件中。我希望這有幫助。

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!")