[英]Python : * Operator in list comprehension
Evening all, I have recently discover the * operator to unpack my list.总而言之,我最近发现了 * 运算符来解压缩我的列表。 I find it quite elegant but I am a bit struggling with it.
我觉得它很优雅,但我有点挣扎。
Please find below an example:请在下面找到一个例子:
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"]]
Is there a way to avoid assigning myself the color, ls and label variables using the * operator?有没有办法避免使用 * 运算符为自己分配颜色、ls 和标签变量? I made a test with: for zip(*list(item)) but I would be grateful for insights or additional documentation.
我用以下方法进行了测试:for zip(*list(item)) 但我将不胜感激您的见解或其他文档。 Thanks a lot, Mat
非常感谢,垫
If you changed the dictionary of lists to a dictionary of dictionaries, you can use the similar **
unpacking operator:如果将列表字典更改为字典字典,则可以使用类似的
**
解包运算符:
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"]
]
This unpacks the dictionaries into the argument list.这会将字典解包到参数列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.