我必须从文本文件中获取元素,对角线,从顶部到按钮.它应该适用于letters.txt的任何维度.该文件看起来像这样:
文本文件:letters.txt(认为这很难,我从原来的帖子中删除了’Y’和’Z’
A B C D E FG H I J K LM 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:
# top to buttomtopButtom_List = [] #should be ['AGMS','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 + 1openfile.close()
我试图用上面的代码做什么:
我试图从文本文件中获取顶部的buttom字符,并将其放入名为topButtom_List的列表中.我使用counter来定义索引,对于外循环所做的每次迭代,索引都会加1.我看到的方式是,外循环将启动,内循环将迭代x4,在第一个topButtom_List中添加AGMS迭代,外部循环将再次迭代并向计数器添加1. BHNTZ将在第二次迭代中添加,依此类推,外部循环将再次迭代并向计数器添加1.
从文本文件:letters.txt
我想填充topButtom_List
输出我得到:
['A','G','M','S']
预期产量:
['AGMS','FLRX']解决方法
#!/usr/bin/python3fIEld = """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 - 1lines,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) breakprint(groups)
返回
List of start and end points: [[(0,0),(0,0)],[(1,1)],[(2,2)],[(3,3)],1),4)],2),5)],3),(1,4),(2,5),(3,5)]]
和
['A','X']总结
以上是内存溢出为你收集整理的Python: *** 作列表全部内容,希望文章能够帮你解决Python: *** 作列表所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)