python的多变量循环

python的多变量循环,python,for-loop,Python,For Loop,我试图理解这段代码中发生了什么。我可以看到它的作用,但它如何到达那里的过程让我难以捉摸 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

我试图理解这段代码中发生了什么。我可以看到它的作用,但它如何到达那里的过程让我难以捉摸

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循环中的多个变量(在这个例子中,
有chars
frags
)。多变量是如何可能的?发生了什么事?python如何处理多个变量?当我在for循环中放入多个变量时,我对python说了什么?在for循环中可以创建多少变量有限制吗?当我对编程理解不够,无法真正形成一个完整的问题时,我怎么能提出一个精确的问题呢

我试着通过python可视化程序运行它,以获得更好的理解。那件事对我来说再清楚不过了。像我经常做的那样尝试。

来自

正如我们前面提到的,Python for循环是基于for的迭代器 环它逐步遍历任何有序序列列表中的项目,即。 字符串、列表、元组、字典键和其他可编辑项。 Python for循环以关键字“for”开头,后跟 任意变量名,它将保存以下变量的值 “序列”对象,它是逐步通过的。一般语法看起来 像这样:

您可以将其迭代为

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
对于os.environ.items()中的k,v:
... 打印“%s=%s”%(k,v)


您可以阅读@iCodez提到的元组解包。在和链接上,他们用适当的例子进行了解释。

这篇文章对理解groupby的工作原理非常有帮助:请看这里:我现在知道我需要搜索的是元组解包或类似的东西。
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
USERPROFILE=C:\Documents and Settings\mpilgrim
OS=Windows_NT
COMPUTERNAME=MPILGRIM
USERNAME=mpilgrim