我试图了解这段代码中发生了什么。我可以看到它的作用,但我无法理解它是如何实现的。
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_chars
和 frags
)。多个变量如何可能?怎么了? python如何处理多个变量?当我在 for 循环中放置多个变量时,我在对 python 说什么?在 for 循环中可以创建多少个变量有限制吗?当我对编程的了解还不足以真正形成一个问题时,我该如何提出一个精确的问题?
我尝试通过 python 可视化工具运行它以获得更好的理解。那件事对我来说从来没有让任何事情变得更清楚。像我经常做的那样尝试。
来自 python-course
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:
for <variable> in <sequence>:
<statements>
else:
<statements>
假设你有像这样的元组列表
In [37]: list1 = [('a', 'b', 123, 'c'), ('d', 'e', 234, 'f'), ('g', 'h', 345, 'i')]
你可以迭代它,
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)
USERPROFILE=C:\Documents and Settings\mpilgrim
OS=Windows_NT
COMPUTERNAME=MPILGRIM
USERNAME=mpilgrim
您可以阅读@iCodez 提到的元组解包。在Tuples in Python和 Unpacking Tuples链接,他们用适当的例子解释了它。