繁体   English   中英

使用 1 个列表理解而不是 3 个使用枚举 Python 组合两个不同的索引搜索

[英]Use 1 list comprehension instead of 3 to combine two different index searches using Enumerate Python

嗨,我想知道是否可以在一个列表条件中运行两个不同的枚举条件:

mlist = ['a', 'boy 808', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'a', 'boy 808', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

loc = [(a,b), a for a, b for b, zip(x in enumerate(mlist), y in enumerate (mlist)) if '808' in x, if 'd' in y]
print(loc)

这可能吗? 我尝试了上述方法,但出现了无效的语法错误:

 File "c:\Users\sys_nsgprobeingestio\Documents\dozie\odfs\ctests.py", line 118
    loc = [(a,b), a for a, b for b, zip(x in enumerate(mlist), y in enumerate (mlist)) if '808' in x, if 'd' in y]
                      ^
SyntaxError: invalid syntax

我想获得所需的输出: [(1,3), (12,14)]澄清一下,这只是一个示例数组。 此逻辑将用于关键字多次出现的大文件中。 这里的词开始和结束文件的一个部分。 我希望得到每个部分的头部和尾部的有序对

每次出现的有序元组列表

我能够使用 3 种不同的列表理解得到我需要的东西。 我想知道您是否可以一次性完成

mlist = ['a', 'boy 808', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'a', 'boy 808', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

blist = [i for i,x in enumerate(mlist) if 'boy' in x ]
dlist = [i for i,x in enumerate(mlist) if 'd' in x ]

tuplist = [(a,b) for a, b in zip((x for x in blist), (y for y in dlist)) ]
print(tuplist)

您可以简单地zip您的blistdlist列表:

mlist = ['a', 'boy 808', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'a', 'boy 808', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']

tuplist = list(zip([i for i,x in enumerate(mlist) if 'boy' in x],
                   [i for i,x in enumerate(mlist) if 'd' in x]
                  )
              )
print(tuplist)

Output:

[(1, 3), (12, 14)]

如果boy值总是与d值交错,您可以通过同时检查两个值来将理解减少到 1:

dlist = [i for i, x in enumerate(mlist) if 'boy' in x or 'd' in x]
tuplist = list(zip(dlist[::2], dlist[1::2]))
print(tuplist)

暂无
暂无

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

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