使用列表推导和for循环 - Python以相反的顺序逐行打印嵌套列表

问题描述 投票:1回答:3
my_list =[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

我正在尽我所能打印形式的my_list

3 2 1
6 5 4
10 9 8 7

这是我的输出:

1 2 3
4 5 6
7 8 9 10

“python方式”看起来很简单,谢谢!

python python-2.7 for-loop printing nested-lists
3个回答
1
投票

方法1

我们可以使用列表理解,切片和.join()运算符。

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

for item in my_list:
    print ' '.join(str(x) for x in item[::-1])

输出:

3 2 1
6 5 4
10 9 8 7

方法2

我们可以使用嵌套for循环和Slices运算符。

for xs in my_list:
    for x in xs[::-1]:
        print x,
    print

并且print()默认情况下会在最后打印换行字符,除非您使用:print(end="")或者如果您使用的是Python 2.x print t,将起作用。

输出:

3 2 1
6 5 4
10 9 8 7

1
投票

我能想出的最简单的答案是:

for nested_list in my_list:
  print([val for val in nested_list[::-1]])

正如在其他答案中所表达的那样,将::-1传递给嵌套列表会反转for循环中的顺序。


0
投票

[:: - 1]切片反转for循环中的列表(但实际上不会“永久地”修改列表):

def reverse_list(my_list):
    new_list = []
    for sub_list in my_list:
        new_list.append(sub_list[::-1])
    return new_list


test_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]];
reversed_lists = reverse_list(test_list)
for reversed_list in reversed_lists:
    print reversed_list
© www.soinside.com 2019 - 2024. All rights reserved.