首页 > 解决方案 > Python 在列表上使用 len 时,如何解决 < 的 TypeError?

问题描述

仍然在这里学习并为我的课程做最后的项目。这是问题所在:我正在尝试写入一个新文件,同时浏览一个列表并检查列表中这些项目的另一个文件。如果找到它们,则应该将它们添加到新文件中。现在,我收到一个 TypeError:

Traceback (most recent call last):
      File "C:/Users/jesse/OneDrive/Documents/PycharmProjects/KimmelFreeman_CMIT450_Project/KimmelFreeman_CMIT450_Project.py", line 154, in <module>
        while x < len(list1):
    TypeError: '<' not supported between instances of 'str' and 'int'

我正在尝试检查 x 是否小于列表的 len 以继续检查。我这样做是因为之前我只能让它返回列表中位置 0 的值。现在,我根本无法让它工作。超级沮丧。我尝试在 len 周围添加 str(),但随后 x+=1 产生了错误。显然我没有正确地做到这一点。我检查了类似的帖子,但找不到,但如果有,请指出那个方向。

我所期望的是,代码将通过列表运行并根据输入文件进行检查,如果找到肯定结果,请将其保存到新文件中。

我不确定你们需要查看哪些部分,而且代码很多,所以我将包括产生错误的区域:

# Ask user for needed keywords or symbols
user_keywords = input("What keywords or special symbols would you like to search the provided file for?\n"
                      "Please separate each entry with a comma.\nIf you would like to just search for question marks,"
                      " please just type n.\n")
# Holding list, using comma as a way to separate the given words and symbols
list1 = list(user_keywords.split(','))
# Print list for user to see
print("You have entered the following keywords and/or special symbols: ", list1)

outFileName = input()
outFile = open(outFileName,'w')

def filter_lines_by_keywords(lines_to_filter, key_words):
    key_words_s = set(key_words)
    return filter(lambda l: set(l.split()) & key_words_s, lines_to_filter)

for x in list1:
    outFile.write('Results for keywords and symbols:' + '\n')
    i =0
    while i < len(list1):
        res = filter_lines_by_keywords(lines_to_filter= file1lines, key_words= list1)
        outFile.write(str(list(res)))
        i += 1

outFile.close()

让我知道是否需要添加更多代码。谢谢!

编辑 更新以反映如何list1制作。我使用的是相同的变量。菜鸟失误。但是,即使我更改了代码并修复了同一变量的问题,我也无法让代码移出列表中的第一个位置以查看其中的其他项目。有任何想法吗?我究竟做错了什么?

标签: pythonpython-3.xtypeerror

解决方案


推荐阅读