首页 > 解决方案 > 如何将单个字符与列表中的元素分开?

问题描述

我正在处理一项作业,问题绘制了一个由正方形 AJ 和 1-7 组成的网格。存在一个随机生成坐标的函数,例如

[['I5'],                    
['E1', 'F1', 'E2', 'F2'],
['J5', 'J6'],
['G7', 'H7']]

要解决的问题需要一个函数来读取每个列表中的元素并使用 Turtle 在那里绘制一个图块。

如何将每个列表中的字母与数字分开?

只是为了测试,我试图打印每个坐标(这样我可以更好地理解,最终结果实际上需要 goto(x,x) 然后调用我已经定义的函数来绘制一些东西):

 for instructions in fixed_pattern_16:
        print(instructions[0][1])

哪个输出:

5
1
5
7

但是因为每个列表的长度不同,当我尝试访问位置比最短列表的长度长的元素时,我会遇到超出范围的错误。例如:

print(instructions[2][0])

标签: python-3.xstringlist

解决方案


尝试正则表达式和一些嵌套列表理解:

import re

lists = [['I5'],['E1', 'F1', 'E2', 'F2'],['J5', 'J6'],['G7', 'H7']]

### General format to unpack the list of lists
for i in lists: # Go through each list element
    for x in i: # Go through each element of the element
        print(x) # Print that element to the console

### Flattening that gives us our list comprehension,
### which we can use to unpack this list of lists
[print(x) for i in lists for x in i]

### We want to find a single alphabetic value and capture a single numeric value
### In short, \w looks for a word (letter) and \d looks for a number
### Check out https://regexr.com/ for more info and an interactive canvas.
letter_number_pat = r'\w(\d)'


### We can use re.sub(<pattern>, <replacement>, <string>) to capture and keep our
### numeric value (\1 since it is the first capture group
### Then, we'll anticipate the need to return a list of values, so we'll go with
### the traditional newline (\n) and split our results afterward
number_list = '\n'.join([re.sub(letter_number_pat, r'\1', x) for i in lists for x in i]).split('\n')

输入:number_list

输出:['5', '1', '1', '2', '2', '5', '6', '7', '7']

您可以通过调用 set() 函数并将其包装在标准库中的 list() 和 sorted() 函数中来获取唯一值:

输入:sorted(list(set(number_list)))

输出:['1', '2', '5', '6', '7']


推荐阅读