我尝试列出以“\t”开头的所有安装点:
with open("/proc/mounts") as f:
mountpoints = (
[list((filter(lambda s: s.startswith("/t"), line.split(" "))))
for line in f if
(lambda l:
list(filter(lambda x: x.startswith("/t"), l))
)(line.split(" "))])
print(mountpoints)
#[['/tmp']]
#this is correct, however I want to remove one pair of brackets
print(*mountpoints)
#['/tmp']
#this works!
m = *mountpoints
#SyntaxError: can't use starred expression here
#but this doesn't.
Run Code Online (Sandbox Code Playgroud)
为什么最后一个作业不起作用?与 print 语句有什么区别?
感谢帮助!
*解包将迭代“传播”到封闭的“容器”中。对于 的调用print,容器是函数调用的括号。不过m = *mountpoints,右侧并不在任何东西内部,因此无法将其解压。来自文档:
星号 * 表示可迭代解包。它的操作数必须是可迭代的。可迭代对象被扩展为一系列项目,这些项目包含在解包位置的新元组、列表或集合中。
如果你想删除一层嵌套,并且内部列表将始终包含一个元素,你可以只索引它:
m = mountpoints[0]
Run Code Online (Sandbox Code Playgroud)