繁体   English   中英

检查几个带有多个for循环的列表

[英]check several lists with several for loops

keylist = ['A/P', 'A/Q', 'B/P', 'B/Q', 'C/P', 'C/Q']
List = ['A','B','C']

我想对List中的每个元素和keylist每个元素进行操作:

for n in List:
    for key in keylist:
        if key.split('/')[0] == List[n] and key.split('/')[-1] == 'P':
            try:
                print(n) #placeholder
            except:
                pass

基本上,我想检查keylist的第一个split元素是否是List的元素,但是Output是一个错误:

TypeError: list indices must be integers or slices, not str

因为您在List [n]中使用的n不是List中元素的索引。

for n in List:    # here n is not the index to element in list but element itself. 
    for key in keylist: # so you can't use List[n] below e.g. n is 'A' in first iteration
        if key.split('/')[0] == List[n] and key.split('/')[-1] == 'P':
            try:
                print(n) #placeholder
            except:
                pass

如果需要列表中元素的索引,请使用以下代码。

for idx, ele in enumerate(List):
    for key in keylist:
        if key.split('/')[0] == List[idx] and key.split('/')[-1] == 'P':
            try:
                print(List[idx])  # or print(ele)
            except:
                pass

在这里, ele == List[idx]

keylist = ['A/P', 'A/Q', 'B/P', 'B/Q', 'C/P', 'C/Q']
List = ['A','B','C']

for n in List:
    for key in keylist:
        if ((key.split('/')[0] in List) and (key.split('/')[1] == 'P')):
            try:
                print(n) #placeholder
            except:
                pass

PythonZen保持一致。

扁平比嵌套更好

for key in keylist:
    s = key.split('/')
    if s[0] in List and s[-1] == 'P':
        try:
            print(s[0]) #placeholder
        except:
            pass

只要List中的元素是唯一的,这将起作用。 您的算法将为List重复项复制输出。 此算法不会。

暂无
暂无

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

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