[英]Python : * Operator in list comprehension
总而言之,我最近发现了 * 运算符来解压缩我的列表。 我觉得它很优雅,但我有点挣扎。
请在下面找到一个例子:
from matplotlib.pyplot import Line2D
COLOR_FCT = {
"a": ["blue", "Al", "-"],
"b": ["orange", "Bv", "-"],
"c": ["green", "Cx", "-"],
"d": ["k", "Ds", "--"],
}
legend = [
Line2D(
[0],[0],color=COLOR_FCT[item][0],lw=2,ls=COLOR_FCT[item][2],label=COLOR_FCT[item][1],)
for item in ["a", "b", "c"]]
有没有办法避免使用 * 运算符为自己分配颜色、ls 和标签变量? 我用以下方法进行了测试:for zip(*list(item)) 但我将不胜感激您的见解或其他文档。 非常感谢,垫
如果将列表字典更改为字典字典,则可以使用类似的**
解包运算符:
COLOR_FCT = {
"a": {"color": "blue", "label": "Al", "ls": "-"],
"b": ["color": "orange", "label": "Bv", "ls": "-"],
]
legend = [
Line2D([0],[0], **COLOR_FCT[item])
for item in ["a", "b", "c"]
]
这会将字典解包到参数列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.