简体   繁体   English

Python 嵌套列表理解迭代两个列表元素

[英]Python nested list comprehension iterate over both list elements

Given the following list of lists which has a length of 2:给定以下长度为 2 的列表:

cLists = [[(1.3, "30__[1.353, '12', 'weekly']_[1.35, '20', 'daily']"), (1.35, '0_Retrace_50_M')], [(1.34, "32__[1.34, '11', 'weekly']_[1.34, '12', 'daily']"), (1.3459, '1_Ret_50_W')]]

len(cLists)
2

I can use a list comprehension on list index 1 cLists[1] as follows:我可以在列表索引 1 cLists[1]上使用列表理解,如下所示:

[level_description[1] for level_description in cLists[1] 
                    if any(k in level_description[1] for k in ['daily','weekly','monthly'])]

However I am struggling to iterate over both elements of the list cLists[0] and cLists[1]但是我正在努力迭代列表cLists[0]cLists[1]的两个元素

How do I iterate over both elements of this list?如何迭代此列表的两个元素?

Assuming you want a nested list of results to match the input, you can just nest your list comprehensions:假设你想要一个嵌套的结果列表来匹配输入,你可以嵌套你的列表推导:

[[ld[1] for ld in cList if any(k in ld[1] for k in ['daily','weekly','monthly'])] for cList in cLists]

Output: Output:

[
 ["30__[1.353, '12', 'weekly']_[1.35, '20', 'daily']"],
 ["32__[1.34, '11', 'weekly']_[1.34, '12', 'daily']"]
]

If you don't want a nested list, you just need to add a for expression over the cLists values:如果你不想要一个嵌套列表,你只需要在cLists值上添加一个for表达式:

[ld[1] for cList in cLists for ld in cList if any(k in ld[1] for k in ['daily','weekly','monthly'])]

Output: Output:

[
 "30__[1.353, '12', 'weekly']_[1.35, '20', 'daily']",
 "32__[1.34, '11', 'weekly']_[1.34, '12', 'daily']"
]

Not sure if this is what your looking or not...不知道这是否是你想要的......

aa = []
for i in cLists:
    aa.append([level_description[1] for level_description in i 
                if any(k in level_description[1] for k in ['daily','weekly','monthly'])])

aa then being a list of matches. aa 然后是匹配列表。

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

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