python - 列表外的 "list comprehension"样式语法?

标签 python list-comprehension

我发现列表理解语法非常有用且紧凑。在一直使用它之后,它让我想在列表之外使用它,例如我想更改:

s="sausages hamsters"
intermediate=" and "
word1,word2=s.split()
s2=word1+intermediate+word2

进入

word1,word2=s.split()
s2=word1+intermediate+word2 for word1,word2 in s.split

显然这行不通。 我在这里遗漏了什么或者这根本无法在一行中完成吗?

编辑:当然这个例子很愚蠢,但在某些情况下我可以看到这节省了不止一行

编辑:我只是写了这个例子,让它读起来更愉快,但我的问题的更多文字版本是:

“有没有办法在一个声明中以这种方式创建变量:

newVar= <expression using still undefined variables> \  
        <some keyword or symbols> \  
         <declaration of pre-cited undefined variables>

就像列表理解允许做的那样:

newList=[<expression using still undefined variables>  
    for <declaration of pre-cited undefined variables, as result of an iterator>]

如果我们可以构建列表,是否也可以构建简单的单个对象?”

最佳答案

你想要str.join()这里:

' and '.join(s.split())

每当您想连接多个字符串时,无论字符串之间是否有文本,str.join() 都将是比每个字符串连接更快的选择。

由于 str.join() 采用可迭代参数,您可以根据需要使用生成器表达式和列表推导式。列表理解会更好(因为它是 faster for str.join() )

至于更“通用”的类似列表理解的语法;在生成器表达式、各种理解格式(list、set 和 dict)和 next() 函数之间,您真的不需要更复杂的语法。

请记住,可读性也很重要;不要尝试在循环没有意义的地方应用循环。作为一种反模式,您的“循环中的一个对象”示例可能是:

result = next(a + foo + b for a, b in (s.split(),))

我将 s.split() 结果的单独赋值强加到生成器表达式中。该表达式很难解析,您不应该为了在不需要循环的地方使用循环而使用它

关于python - 列表外的 "list comprehension"样式语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22229133/

相关文章:

python - 计算两个列表中数字的出现次数并返回一个列表

python - 如何通过检查 python 子列表中的值来对列表进行排序?

python - 如何在 sqlalchemy 模型中添加自定义函数/方法来进行 CRUD 操作?

python - RichIPythonWidget 导入对 pkgutil 模块的副作用

python - 如何使用 itertools.groupby() 获取每个项目的索引和出现

python - 用其他项目替换 python 列表理解中 dict 中的单个值

python - UnicodeDecodeError : 'utf-8' codec can't decode byte 0xe2 in position 1023: unexpected end of data

python - 在带有噪声边的矩形周围找到已知大小的旋转边界框

python - 用列表理解替换一周内的 for 循环

python - 在给定条件的情况下访问 Python 中另一个列表的列表