我正在研究python中的切分方法。在这里,我将文本文件的文本拆分为列。我想改变元素的顺序,这意味着如果文本在A、B和C列中出现,我现在想在A、C和B列中显示文本。我的程序如下
import sys
def first(aList):
for row in colList:
for item in row:
print(item, end=" ")
print()
ncolumns = int(input("Enter Number of Columns:"))
file = open("alice.txt", "r")
rowL= []
colList= []
print(" ")
print(" ")
print("++++++++++++++++++++++++++++++++++++++")
while True:
line = file.readline()
if not line:
break
numElements = len(line.rstrip())
_block= numElements//ncolumns
block = _block
start=0
rowL =[]
for count in range(0,(ncolumns)):
columnChars = ""
for index in range(start,block):
columnChars += line[index]
rowL.append(columnChars)
start = block
block = block + _block
if (block < numElements):
if((block + _block)>numElements):
block = numElements
colList.append(rowL)
file.close()
first(colList)
只需创建一个新列表,对旧列表中的元素进行索引
就是说,
这将把
new_list
作为[0, 3, 2]
在这里使用切片分配
如果你不明白的话,看看^{}
相关问题 更多 >
编程相关推荐