与for循环一起使用的字符串join()方法 [英] String join() method used with for loop

查看:577
本文介绍了与for循环一起使用的字符串join()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要您的帮助,因为我不明白为什么可以将join()方法与for循环作为参数一起使用.

I need your help, because I don't understand why is possible to use the join() method with a forloop as an argument.

例如:

" ".join(str(x) for x in list)

Python文档:

str.join(iterable) 返回一个字符串,该字符串是可迭代的字符串的串联.

str.join(iterable) Return a string which is the concatenation of the strings in iterable.

如果可迭代项中有任何非字符串值(包括字节对象),则会引发TypeError.元素之间的分隔符是提供此方法的字符串.

A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

可以请人解释吗?

推荐答案

语句(str(x) for x in list)被称为生成器表达式:

>>> (str(x) for x in [1,2,3])
<generator object <genexpr> at 0x7fc916f01d20>

这是创建一个对象,该对象可以被精确地迭代一次,并产生一次可以创建的元素.您可以像列表一样遍历它,如下所示:

What this does is create an object that can be iterated over exactly once, and yields elements that would be created one at a time. You can iterate over it as you would a list, like this:

>>> gen = (str(x) for x in [1,2,3])
>>> for s in gen:
...     print s
... 
1
2
3

生成器表达式是可迭代的,因此join函数的作用是对其进行迭代并连接其值.

A generator expression is iterable, so what the join function does is iterate over it and join its values.

这篇关于与for循环一起使用的字符串join()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆