我正在python中研究cut-up方法。在这里,我将文本文件的文本分解为列。我想改变元素的顺序,也就是说,如果文本进入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)
只需创建一个新列表,对旧列表中的元素进行索引。
也就是说,
old_list = [1, 2, 3]
new_list = [old_list[0], old_list[2], old_list[1]]
这将给出CCD_ 1作为CCD_。
您在此处使用切片分配。
lst= [0,1,2]
lst[1:]=lst[1:][::-1]
print(lst)
# [0, 2, 1]
如果你没有得到How slicing as assignment works
,请看一看。