【问题标题】:length of list in python?python中列表的长度?
【发布时间】:2012-12-15 18:11:16
【问题描述】:

我让用户输入要打开的包含数字的文件。我希望输出是文件中元素的数量。我把..

file=open(input("Please enter the name of the file you wish to open:" ))#, "r")
A= file.readline()

print (A)

n=len(A)
print (n)

我对此很陌生。我正在测试它的文件有 9 个数字(其中 2 个是负数)。长度为 21。如何更改它以获得元素的数量?

【问题讨论】:

  • 文件看起来如何?每行一个数字?数字用空格隔开?
  • 你输入文件的格式是什么?它们是用空格还是逗号分隔?具体的例子在这里会有所帮助。
  • 是(像这样:1 -3 10 6 5 0 3 -5 20)

标签: python string-length


【解决方案1】:

如果数字都在该行,请使用split 将字符串分隔为单独的数字:

# List of strings: ['1', '-3', '10', ...]
numbers = A.split()

print len(numbers)

您可能还想将这些数字从字符串形式转换为整数形式:

# List of numbers: [1, -3, 10, ...]
numbers = [int(n) for n in A.split()]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2013-12-07
    • 2021-04-15
    • 2018-04-21
    • 2018-01-20
    相关资源
    最近更新 更多