简体   繁体   English

for循环在python中如何工作?

[英]How for loop works in python?

I have a lists of lists in variable lists something like this: 我在类似这样的变量lists有一个列表列表:

[7, 6, 1, 8, 3]
[1, 7, 2, 4, 2]
[5, 6, 4, 2, 3]
[0, 3, 3, 1, 6]
[3, 5, 2, 14, 3]
[3, 11, 9, 1, 1]
[1, 10, 2, 3, 1]

When I write lists[1] I get vertically: 当我写lists[1]我会垂直得到:

6
7
6
3
5
11
10

but when I loop it: 但是当我循环它时:

for i in list:
    print(i)

I get this horizontally. 我水平得到这个。

7
6
1
8
3
etc...

So, how it works? 那么,它是如何工作的呢? How can I modify loop to go and give me all vertically? 我如何修改循环以垂直地给我全部?

Short answer: 简短答案:

for l in lists:
   print l[1]  

Lists of lists 清单清单

list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list in list_of_lists:
    for x in list:
        print x

Here is how you would print out the list of lists columns. 这是打印列列表列表的方式。

lists = [[7, 6, 1, 8, 3],
[1, 7, 2, 4, 2],
[5, 6, 4, 2, 3],
[0, 3, 3, 1, 6],
[3, 5, 2, 14, 3],
[3, 11, 9, 1, 1],
[1, 10, 2, 3, 1]]

for i in range(0, len(lists[1])):
    for j in range(0, len(lists)):
        print lists[j][i],
    print "\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM