如何在python中更改2d列表的顺序

2024-09-23 06:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究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)  

Tags: in文本foriflineblockstartfile
2条回答

只需创建一个新列表,对旧列表中的元素进行索引

就是说,

old_list = [1, 2, 3]
new_list = [old_list[0], old_list[2], old_list[1]]

这将把new_list作为[0, 3, 2]

在这里使用切片分配

lst= [0,1,2]
lst[1:]=lst[1:][::-1]
print(lst)
# [0, 2, 1]

如果你不明白的话,看看^{}

相关问题 更多 >