【发布时间】:2014-11-28 03:11:51
【问题描述】:
这是一个反映我目前正在处理的代码的示例:
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 内的执行流程,以便语句在各自的范围内,而不是一次执行所有语句。如果真有那么不可思议的话,它会让嵌套循环的创建变得如此简单,代码少得多,而且格式化它几乎不费吹灰之力。
感谢您花时间阅读我的问题,任何帮助将非常非常感谢
【问题讨论】:
-
为什么需要一个列表理解?
-
嘿 wwii(大粉丝),列表推导式看起来如此优雅,对我来说,如果我只能访问每个 for 列表中的范围,那么执行复杂的语句将非常容易。此外,关于代码的循环部分,您将使用少 1/3 - 1/4 的代码
标签: python list python-3.x list-comprehension control-flow