【问题标题】:len() function shows 45 values as opposed to 90 values which it should, what am i doing wrong?len() 函数显示 45 个值,而不是它应该显示的 90 个值,我做错了什么?
【发布时间】:2019-05-16 07:50:15
【问题描述】:

这是我使用 txt 文件制作列表的代码,打印效果很好,显示它包含 90 个值:

read_txt = open("Data.txt", "r")

my_list = read_txt.readlines()

for values in my_list:
    if not values.startswith("#"):  # ignores the header comment in the text file
        values = values.rstrip("\n") # strips \n from end of each value

        print(values)

read_txt.close()

print(len(values))

但是print(len(values)) 给出的是 45。

【问题讨论】:

  • 我不明白这个问题。当我写 a = [1,2,4,'b','c'];长(一);这给出“5”。没有类型错误。你能举一个更具体的例子来说明你在做什么吗?
  • @jubba 请在您的帖子中添加一些代码,以便我们了解您要做什么。
  • “我意识到这是因为存在 int 和 string 值”不,绝对不是。 len 不关心你列表中的对象类型你需要提供一个minimal reproducible example
  • 提供一些示例数据和您的代码,以使您的问题更加具体。
  • 我意识到我做错了什么,现在让 len() 给我一个值,但是该值应该是 90,它返回 45。

标签: python string list int


【解决方案1】:

len([1,2,'a','b']) 不会为您提供列表中元素数量的唯一解释是,如果您有一个重新定义 __len__ 函数的类。如果你有,请检查你的班级

  def __len__(self):
      #defined differently

否则问题出在其他地方:)

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    相关资源
    最近更新 更多