多变量for循环python

2024-03-29 08:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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可视化程序运行它以获得更好的理解。那件事对我来说再清楚不过了。像我经常做的那样。


Tags: the代码foristhisfirstboolhas
1条回答
网友
1楼 · 发布于 2024-03-29 08:36:19

来自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提到的tuple解包。在Tuples in PythonUnpacking Tuples链接处,他们用适当的例子解释了这一点。

相关问题 更多 >