我试图通过将元组第一项与指定的 int() 进行比较来打印元组列表,但由于某种神秘原因,第二项中为 0 的元组消失了
编码:
n_vertical = 3
n_horizontal = 3
for x in range(0,n_vertical):
for y in range(0,n_horizontal):
area.append((x,y,0))
print(area)
print('''
''')
def representacao_do_mapa(modo):
if modo == 1:
n=0
l_c = []
for x in area:
if x[0] == n:
l_c.append(x)
else:
print(l_c)
l_c = []
n+=1
representacao_do_mapa(1)
文本输出:
[(0, 0, 0), (0, 1, 0), (0, 2, 0)]
[(1, 1, 0), (1, 2, 0)]
问题
x
创建新列表时,您正在丢弃元组:
if x[0] == n: l_c.append(x) # here you append x else: print(l_c) # here you print but do nothing with x l_c = [] # list empty, x is missing n+=1
解决方案
def representacao_do_mapa(modo):
if modo == 1:
n=0
l_c = []
for x in area:
if x[0] == n:
l_c.append(x)
else:
print(l_c)
l_c = [x] # fix here
n+=1
print(l_c) # fix here
representacao_do_mapa(1)
除此之外 - 你的最后一个列表不会被打印,因为最后一个列表l_c
永远不会进入你的代码的打印部分 - 你必须在区域的 for 循环之外添加它。
输出(对于n_vertical = 3
和n_horizontal = 3
:
[(0, 0, 0), (0, 1, 0), (0, 2, 0)]
[(1, 0, 0), (1, 1, 0), (1, 2, 0)]
[(2, 0, 0), (2, 1, 0), (2, 2, 0)]
优化:
您可以使用列表推导式和列表分解来缩短代码:
n_vertical = 3
n_horizontal = 3
area = [ (x,y,0) for x in range(n_horizontal) for y in range(n_vertical )]
# create with inner lists
area2 = [ [(x,y,0) for x in range(n_horizontal)] for y in range(n_vertical)]
print(area)
# print each inner list on new line
print(*area2, sep="\n")
或者您可以直接从area
以下位置打印:
print(* (area[i*n_horizontal:i*n_horizontal+n_horizontal]
for i in range(n_vertical)) , sep="\n")
使用发电机表达切片area
成n_horizontal
片。
有关生成器/列表表达式的更多信息:生成器表达式与列表理解
有关分块列表的更多信息:如何将列表拆分为大小均匀的块?
有关列表切片的更多信息:了解切片符号
更多关于打印:https : //docs.python.org/3/library/functions.html#print
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句