python – 如何在列表推导中分配函数调用

前端之家收集整理的这篇文章主要介绍了python – 如何在列表推导中分配函数调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试优化一些代码来处理列表列表,我注意到当我尝试在列表中指定一个列表时,我会一直遇到语法或输出错误.

我的代码如下

out = []
for cluster in ClusterFile:
    cluster = list(cluster)
    for term in cluster[3]:
        for item in Interest:
            if term == item[0]:
                x = [item[1]]
                cluster.append(x)
                break
        out.append(cluster)
        break

我的许多尝试之一:

out = [([item[1]]) for item in Interest for term in cluster[3] if term ==item[0] for cluster in ClusterFile]

输入示例:

cluster = [['a'],[1,2],[3,4],[['w'],['x'],['y'],['z']],[5,6]]

Interest = [['w','qx12'],['y','qx19']]

示例输出

[['a'],6],['qx12','qx19']]

有谁知道任何可以帮助我解决这个问题的资源?我在Python 3中编码

最佳答案
虽然我同意@blacksite的说法列表理解并不是最容易理解的方式,但如果这是你的目标,那么这里是如何做到的:

cluster.append(
    [x[0] for x in [[item[1] for item in Interest if term[0] == item[0]] 
                    for cluster in ClusterFile for term in cluster[2]] 
     if len(x)]
)

cluster
# [['a'],'qx19']]

数据:

cluster = [['a'],6]]
ClusterFile = [cluster]
Interest = [['w','qx19']]

几点说明:

>嵌套列表推导与嵌套for循环的顺序相同.所以如果你有:

for a in b:
    for x in a:
        f(x)

那么这看起来像:

[f(x) for a in b for x in a]

这看起来有点倒退,因为a中的x远离声明使用x的前面.只需将其视为嵌套for循环的顺序即可. (你在原始代码中倒退了.)
>你想要集群[2],而不是集群[3].
>在群集[2]中选择单个元素时,例如[‘w’],[‘x’]等,您正在比较列表元素([‘w’]),由term表示该列表中包含的字符串(‘w’),由item [0表示].这不匹配,你需要使用term [0].
>附加的最终列表(x [0] s列表)会删除一些在内部列表理解中创建的空列表.这不是很漂亮,可能有更好的方法.但同样,在我看来,如果没有列表理解,这整个方法会更具可读性.

原文链接:https://www.f2er.com/python/438924.html

猜你在找的Python相关文章