Python:操作列表

标签 python list python-3.x

<分区>

问题

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

文本文件:letters.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 添加 AGMS 在第一次迭代的topButtom_List中,外层循环会再次迭代并给counter加1。 BHNTZ 将在第二次迭代时添加,依此类推,外层循环将再次迭代并将计数器加 1。

来自文本文件:letters.txt 我想填充 topButtom_List

我得到的输出:

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

预期输出:

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

最佳答案

#!/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']

关于Python:操作列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086537/

相关文章:

python - 在带有 'safe' 参数的 utf-8 字符串上使用 python 的 urllib.quote_plus

python - CheckboxSelectMultiple 不使用 Django-Material 显示复选框

python - 根据另一个键过滤字典列表以删除键中的重复项

c# - C#中的linq to List问题

python - 循环遍历文件并同时使用 `file.readline()` 是 "ok"的做法吗?

python - 如何为布局添加边框?

python - 如何从列表或 numpy 数组构造字典?

c# - 为什么我们有时在初始化时不使用括号?

python - 使用 Python 脚本将长视频切成 FFMPEG 中的 block

python - 使用 multiprocessing.pool.map 通过同一个套接字发送