我正在做一个作业,该问题绘制了一个正方形的A-J和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])
答案 0 :(得分:0)
尝试正则表达式和一些嵌套列表理解:
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']