首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:操作列表

Python:操作列表
EN

Stack Overflow用户
提问于 2016-05-07 08:57:18
回答 1查看 95关注 0票数 4

问题

我必须从文本文件中获取元素到对角列表,并从顶部到对象。它应该可以在letters.txt的任何维度上工作。该文件如下所示:

文本文件: letters.txt (认为这很难,我从原来的帖子中删除了'Y‘和'Z’

代码语言:javascript
复制
A B C D E F
G H I J K L
M N O P Q R 
S T U V W X

列表应该如下所示:

代码语言:javascript
复制
topButtom_List = ['AGMS', 'BHNT', 'CIOU', 'DJPV', 'EKQW', 'FLRX']

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

当前top到buttom的代码:

代码语言:javascript
复制
# 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的列表中。我用计数器定义了一个索引,对于外部循环所做的每一次迭代,索引都会被加1。在我看来,外循环将开始,内环将在第一次迭代时迭代x4,在topButtom_List中添加AGMS,外部循环将再次迭代,并将1添加到计数器。BHNTZ将在第二次迭代中添加等等,外部循环将再次迭代并将1添加到计数器中。

在文本文件: letters.txt中,我想填充topButtom_List

我得到的输出:

代码语言:javascript
复制
['A', 'G', 'M', 'S']

预期输出:

代码语言:javascript
复制
['AGMS', 'BHNT', 'CIOU', 'DJPV', 'EKQW', 'FLRX']
EN

回答 1

Stack Overflow用户

发布于 2016-05-07 12:48:29

代码语言:javascript
复制
#!/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)

返回

代码语言:javascript
复制
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)]]

代码语言:javascript
复制
['A', 'GB', 'MHC', 'SNID', 'TOJE', 'UPKF', 'VQL', 'WR', 'X']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37086537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档