将元组从列表追加到另一个列表并打印出来的问题

时间:2019-01-19 08:18:34

标签: python python-3.x

我正在尝试通过将元组的第一项与指定的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)

screenshot of output

文本输出:

[(0, 0, 0), (0, 1, 0), (0, 2, 0)]
[(1, 1, 0), (1, 2, 0)]

1 个答案:

答案 0 :(得分:3)

问题

创建新列表时,您将丢弃元组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-loop区域添加该标记。

输出(用于n_vertical = 3n_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个片段。


有关生成器/列表表达式的更多信息:Generator Expressions vs. List Comprehension

有关分块列表的更多信息:How do you split a list into evenly sized chunks?

更多关于列表切片的信息:Understanding slice notation

有关打印的更多信息:https://docs.python.org/3/library/functions.html#print