繁体   English   中英

Python(3.4)列表理解-如何控制执行流程

[英]Python (3.4) List comprehensions - How do you control the flow of execution

这是一个反映我当前正在处理的代码的示例:

def find_match():

    num=[[2, 3, 5, 7, 8, 10, 12], [12, 1, 3, 5, 6, 8, 10], [11, 12, 2, 4, 5, 7, 9]]
    name= ['Type One','Type Two','Type Three']

    match = [[[name[ri], name[ci][5:], list(sorted(set (rv) & set(cv)))]
    for ci,cv in enumerate (num) if rv != cv] for ri,rv in enumerate(num)]

    return match
>>> match=find_match()
[[[3, 5, 8, 10, 12], [2, 5, 7, 12]], [[3, 5, 8, 10, 12], [5, 12]], [[2, 5, 7, 12], [5, 12]]]

再一次,这只是作为一个例子,因此我知道该函数绝不能泛化,实际函数采用一个嵌套列表作为arg,而后者又是通过另一个函数创建的。

与所有其他子列表相比,这将找到每个子列表之间的匹配项

我现在想做的是在新的匹配对列表中为每个匹配项添加一个名称,这是我想要的输出

[['Type One', ['Two', [3, 5, 8, 10, 12]], ['Three', [2, 5, 7, 12]]], ['Type Two', ['One', [3, 5,   
8, 10, 12]], ['Three', [5, 12]]], ['Type Three', ['One', [2, 5, 7, 12]], ['Two', [5, 12]]]]

您会看到,生成字符串名称(例如“ One”)并打印模式,将在嵌套的for循环中的同一行执行中进行,其中一组匹配项(例如“ Type One”)的标题为在外循环内执行。

这是我使用嵌套的for循环所需的输出:

matches=[]
match=[]

for ri,rv in enumerate(num):
    match.append(name[ri])
    for ci,cv in enumerate(num):
        if rv!= cv:
            match.append([name[ci][5:],sorted((list(set(cv) & set (rv))))])

     matches.append(match)
     match=[]

return matches

这使我可以通过索引访问列表的一部分,例如:

>>> match=find_match()
>>> match[0]
['Type One', ['Two', [3, 5, 8, 10, 12]], 'Type One', ['Three', [2, 5, 7, 12]]]
>>> match[0][0]
'Type One'
>>> match[0][1]
['Two', [3, 5, 8, 10, 12]]
>>> match[0][2]
'Type One'

对于LC,它仅返回值列表,但其行为类似于嵌套的for循环,其中所有语句均在最终循环内执行:

for ri,rv in enumerate(num):
    for ci,cv in enumerate(num):
        if rv!= cv:
            match.append(name[ri])
            match.append([name[ci][5:],sorted((list(set(cv) & set (rv))))]) 

这与此LC相同:

match = [[[name[ri], name[ci][5:], list(sorted(set (rv) & set(cv)))]
for ci,cv in enumerate (num) if rv != cv] for ri,rv in enumerate(num)]

这两种都会产生:

[[['Type One', 'Two', [3, 5, 8, 10, 12]], ['Type One', 'Three', [2, 5, 7, 12]]], [['Type Two',     
'One', [3, 5, 8, 10, 12]], ['Type Two', 'Three', [5, 12]]], [['Type Three', 'One', [2, 5, 7,    
12]], ['Type Three', 'Two', [5, 12]]]]

因此,我想知道是否存在一种方法来控制LC中的执行流程,以使这些语句在其各自的范围内,而不是立即执行所有语句。 如果那是令人难以置信的,那么它将使嵌套循环的创建变得如此简单,只需更少的代码,而对其进行格式化几乎是毫不费力的。

感谢您抽出宝贵的时间来阅读我的问题, 非常感谢您的帮助

num = [[2, 3, 5, 7, 8, 10, 12], [12, 1, 3, 5, 6, 8, 10], [11, 12, 2, 4, 5, 7, 9]]
name = ['Type One','Type Two','Type Three']

[[name[ci]] 
 + [[name[ri][5:]] 
    + [sorted(set(cv) & set (rv))]   
    for ri,rv in enumerate(num) if rv!=cv] 
 for ci,cv in enumerate(num)]

产量

[['Type One', ['Two', [3, 5, 8, 10, 12]], ['Three', [2, 5, 7, 12]]],
 ['Type Two', ['One', [3, 5, 8, 10, 12]], ['Three', [5, 12]]],
 ['Type Three', ['One', [2, 5, 7, 12]], ['Two', [5, 12]]]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM