Python:操纵列表

2024-04-19 23:47:33 发布

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

问题

我必须从一个文本文件到一个列表的元素,对角线,从上到下。它应该适用于letters.txt的任何维度。文件如下所示:

文本文件:字母.txt(我觉得这很难,于是从原来的帖子中去掉了“Y”和“Z”。

A B C D E F
G H I J K L
M N O P Q R 
S T U V W X

列表应如下所示:

topButtom_List = ['AGMS', 'BHNT', 'CIOU', 'DJPV', 'EKQW', 'FLRX']

bLeftToURight = ['A', 'GB', 'MHC', 'SNID', 'TOJE', 'UPKF', 'VQL', 'WR', 'X']

从上到下的当前代码:

# top to buttom
topButtom_List = [] #should be ['AGMS', 'BHNT', 'CIOU', 'DJPV', 'EKQW', 'FLRX']

openFile = open("letters.txt")
for i in openFile:
    i = i.replace(" ","")
length = len(i)
openFile.close()

openFile = open("letters.txt")   
counter = 0   
for eachIterration in range(length):
    for line in openFile:
        line = line.replace(" ","")
        # counter should be added by 1 each time inner loop itterates x4, and outter loop x1.
        topButtom_List.append(line[counter]) 
    counter = counter + 1
openFile.close()

我想用上面的代码做什么:

我试图从文本文件中获取从上到下的字符,并将其放入名为topButtom_List的列表中。我使用counter来定义索引,对于外部循环所做的每一次迭代,索引将被加上1。在我看来,外循环将开始,内循环将迭代x4,在topButtom_List中添加AGMS。在第一次迭代中,外循环将再次迭代,并向counter添加1。BHNTZ将在第二次迭代中添加,以此类推,外部循环将再次迭代,并向counter添加1。你知道吗

从文本文件:字母.txt 我想填充topButtom_List

我得到的输出:

['A', 'G', 'M', 'S']

预期产量:

['AGMS', 'BHNT', 'CIOU', 'DJPV', 'EKQW', 'FLRX']

Tags: txt列表linecounterlist文本文件lettersopenfile
1条回答
网友
1楼 · 发布于 2024-04-19 23:47:33
#!/usr/bin/python3

field = """A B C D E F
           G H I J K L
           M N O P Q R
           S T U V W X"""

arr = [col.split(' ') for col in [row.strip() for row in field.split('\n')]]
len_x, len_y = len(arr[0]), len(arr)
len_all = len_x + len_y - 1
lines, groups = [], []

for i in range(len_all):
    start = (i, 0) if i < len_y else (len_y-1, i-len_y+1)
    end = (0, i) if i < len_x else (i-len_x+1, len_x-1)
    lines.append([start, end])

print('List of start and end points: ', lines)

for start, end in lines:
    group = ''
    for i in range(len_x):
        y, x = start[0] - i, start[1] + i
        if y >= 0 and y < len(arr) and x < len(arr[y]):
            group += arr[y][x]
        else:
            groups.append(group)
            break

print(groups)

退货

List of start and end points:  [[(0, 0), (0, 0)], [(1, 0), (0, 1)],
[(2, 0), (0, 2)], [(3, 0), (0, 3)], [(3, 1), (0, 4)], [(3, 2), (0, 5)], 
[(3, 3), (1, 5)], [(3, 4), (2, 5)], [(3, 5), (3, 5)]]

以及

['A', 'GB', 'MHC', 'SNID', 'TOJE', 'UPKF', 'VQL', 'WR', 'X']

相关问题 更多 >