循环python的多变量

multi variable for loops python

本问题已经有最佳答案,请猛点这里访问。

我试图理解这段代码中发生了什么。我能看到它做了什么,但是它如何到达那里的过程让我无法理解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from itertools import groupby
lines = '''
This is the
first paragraph.

This is the second.
'''
.splitlines()
# Use itertools.groupby and bool to return groups of
# consecutive lines that either have content or don't.
for has_chars, frags in groupby(lines, bool):
    if has_chars:
        print ' '.join(frags)
# PRINTS:
# This is the first paragraph.
# This is the second.

我认为我的困惑围绕着for循环中的多个变量(在本例中是has_charsfrags)。多变量如何可能?发生什么事了?python如何处理多个变量?当我在for循环中放入多个变量时,我要对python说什么?在for循环中可以创建多少个变量有限制吗?当我对编程的理解还不足以形成一个精确的问题时,我该怎么问呢?

我试着通过Python Visualiser运行它以获得更好的理解。那件事从来没有让我明白过。像我经常做的那样尝试。


从python课程开始

As we mentioned earlier, the Python for loop is an iterator based for
loop. It steps through the items in any ordered sequence list, i.e.
string, lists, tuples, the keys of dictionaries and other iterables.
The Python for loop starts with the keyword"for" followed by an
arbitrary variable name, which will hold the values of the following
sequence object, which is stepped through. The general syntax looks
like this:

1
2
3
4
for <variable> in <sequence>:
    <statements>
else:
    <statements>

假设你有这样的元组列表

1
In [37]: list1 = [('a', 'b', 123, 'c'), ('d', 'e', 234, 'f'), ('g', 'h', 345, 'i')]

你可以迭代为,

1
2
3
4
5
6
7
8
9
10
11
12
13
In [38]: for i in list1:
   ....:     print i
   ....:    
('a', 'b', 123, 'c')
('d', 'e', 234, 'f')
('g', 'h', 345, 'i')

In [39]: for i,j,k,l in list1:
    print i,',', j,',',k,',',l
   ....:    
a , b , 123 , c
d , e , 234 , f
g , h , 345 , i

for k, v in os.environ.items():
... print"%s=%s" % (k, v)

1
2
3
4
USERPROFILE=C:\Documents and Settings\mpilgrim
OS=Windows_NT
COMPUTERNAME=MPILGRIM
USERNAME=mpilgrim

您可以阅读@icodez所提到的tuple解包。在python中的tuples和解包tuples链接中,他们用适当的例子解释了它。