在列表推导中解开拆分 [英] unpacking a split inside a list comprehension
问题描述
如果我想基于文档行的元素生成元组列表,我可以这样做:
If I want to generate a list of tuples based on elements of lines of a document, i can do :
[(line.split()[0], line.split()[-1][3:8]) for line in open("doc.txt")]
例如
(我添加了切片以显示我可能要对split的元素使用一些操作).
for example (i added the slicing to show that I might want use some operations on the elements of the split).
还是要避免两次使用split,因为这样效率不高.
所以我想使用
Still I would like to avoid using split two times, because that's unefficient.
So I wanted to use something like unpacking, with
[(linesplit0, linesplit1[3:8]) for line in open("doc.txt") for (linesplit0, linesplit1) in line.split()]
但这不起作用,因为拆分中没有元组,因此拆分的每个元素都将缺少一个元素.
but that can't work since there are no tuples in the split, so at each element of the split we will be lacking one element.
我想要的是一种允许使用占位符名称作为拆分结果的列表的名称(如splittedlist或其他内容),并且可以与索引(splittedlist [0])或拆包或两者一起使用,这将与理解列表语法兼容.
What I would like is something that allows to use a placeholder name for the list resulting of the split (like splittedlist or whatever), and that could be used with indexing (splittedlist[0]), or unpacking or both), and that would be compatible with the comprehension list syntax.
可行吗?
推荐答案
您可以在打开时使用map
(python3)或itertools.imap
(python2):
You can use map
(python3) or itertools.imap
(python2) over open:
[(line[0], line[-1][3:8]) for line in map(str.split, open("doc.txt"))]
或使用生成器:
[(line[0], line[-1][3:8]) for line in ( l.split() for l in open("doc.txt"))]
这篇关于在列表推导中解开拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!