python - 多变量for循环python

标签 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 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 可视化工具运行它以获得更好的理解。那件事对我来说从来没有让任何事情变得更清楚。像我经常做的那样尝试。

最佳答案

来自 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 PythonUnpacking Tuples链接,他们用适当的例子解释了它。

关于python - 多变量for循环python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20986463/

相关文章:

javascript - 我对 for 循环中的 javascript let 和 var 感到困惑?

r - 加速 R 中的 for 循环

azure - Azure NSG 资源上的 Terraform 嵌套 For 循环

Java 循环效率 ("for"与 "foreach")

python - 失败前提条件错误: Attempting to use uninitialized value conv2d_1/kernel with Tensorflow/Python

python - 资源的 getChild 没有调用扭曲

python - 如何检测Python中变量的更改位置?

java - 我的方法不允许我在遍历数组时留下 for 循环

python - 如何获取GAE上某个页面的访问者数量?

python - 寻找网络中每一对的最短路径