首页 > 解决方案 > 每当列表元素输出为 true 时都无法获取索引

问题描述

我编写了一个代码,只要找到匹配项,就会将组列表更新为 1。比较是从列表 inp 和列表 a 中逐个元素完成的。组列表正确显示输出,但我无法访问单个列表元素。当我将函数应用为 all(groups) 时,我想确定哪些所有索引的输出为 True

def zerolistmaker(n):
    listofzeros = [0] * n
    return listofzeros

inp=['6161', '03901', '81750', 'BRIN', '610415', 'WADD', '045211', '041577']
a=[['JOSH', 'M', 'WADD', ' ', '41577', '041577'], ['BRIN', 'None', 'WADD', 'None', '045211', '045211'], ['BRIN', 'None', 'WADD', 'None', '81750', '6161'], ['BRIN', 'None', 'WADD', 'None', 'None', '610415770488']]
stopwords=[' ','None']
for i in a:
    #print(i)
    while(' ' in i) : 
        i.remove(' ') 
    while('None' in i) : 
        i.remove('None') 
    #.remove('None')
    #print(i)

    groups=zerolistmaker(len(i))
    #print(groups)
    for k in range(0,len(i)):
        for j in range(0,len(inp)):
            if i[k] == inp[j]:
                #print("String match: ",i[k])
                groups[k]= 1
    print(groups)
    t=[all(groups)]
    print(t)

打印(组)的实际输出:

[0, 0, 1, 0, 1]
[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 0]

当我尝试执行print(groups[3])时,它将第 3 列垂直作为 1,1,1,0。我想将组列表迭代为 group[0] 输出,如下所示,然后我需要将所有函数应用于每个列表。[[0, 0, 1, 0, 1],[1, 1, 1, 1],[1, 1, 1, 1], [1 ,1 0]] 如果可能的话,将组转换为 2D 列表,如下所示:

for i in groups:
    if all(groups[i])==True:
         print("perfect match")
    else:
        print("mismatch in records")

请提出我在这段代码中做错了什么,任何以更好的方式实现结果的即兴创作都将受到赞赏。

标签: pythonpython-3.x

解决方案


我尝试用更惯用的 Python 风格重写您的代码。特别是,我重命名了一些变量,在适当的地方使用集合而不是列表,并使用列表推导。不过,很难说出你的目标是什么,所以这可能不是你所追求的。

whitelist = {
    '6161', '03901', '81750', 'BRIN', '610415', 'WADD', '045211', '041577'
}

lists_of_words = [
    ['JOSH', 'M', 'WADD', ' ', '41577', '041577'],
    ['BRIN', 'None', 'WADD', 'None', '045211', '045211'],
    ['BRIN', 'None', 'WADD', 'None', '81750', '6161'],
    ['BRIN', 'None', 'WADD', 'None', 'None', '610415770488']
]

stopwords = {' ', 'None'}

for words in lists_of_words:
    print(words)
    # Filter out the words in stopwords.
    filtered = (w for w in words if w not in stopwords)
    # Check which words are in whitelist.
    groups = [w in whitelist for w in filtered]
    print(groups)
    # Find index of first False in groups.
    if False in groups:
        index = groups.index(False)
        print(f"Word at index {index} did not match")
    else:
        print("All words matched.")

这是输出:

['JOSH', 'M', 'WADD', ' ', '41577', '041577']
[False, False, True, False, True]
Word at index 0 did not match
['BRIN', 'None', 'WADD', 'None', '045211', '045211']
[True, True, True, True]
All words matched.
['BRIN', 'None', 'WADD', 'None', '81750', '6161']
[True, True, True, True]
All words matched.
['BRIN', 'None', 'WADD', 'None', 'None', '610415770488']
[True, True, False]
Word at index 2 did not match

推荐阅读