python如何统计列表的长度

有一组数据存放在a.txt,按行存储:
1 2 3 4 5 6
4 5 6 7
2 3 2 3 4 5 7

现在要统计出每行的长度(就是有几个数字),并将长度大于5的记录下行号和长度,存放到b.txt
1 6
3 7

求大神解答!

array = [0,1,2,3,4,5] ;

print len(array) 6;

同样,要获取一字符串的长度,也是用这个len函数,包括其他跟长度有关的,都是用这个函数。

L1=len(list1)   #列表list1的长度 

list2=list(set(list1))  #可以用set,直接去掉重复的元素 

[456, 'abc']print "First list length : ", 

len(list1);print "Second list length : ", len(list2);

扩展资料:

Python 是一门有条理的和强大的面向对象的程序设计语言,类似于Perl, Ruby, Scheme, Java。

自从20世纪90年代初Python语言诞生至今,它已被逐渐广泛应用于系统管理任务的处理和Web编程。

以下实例展示了 len()函数的使用方法:

#!/usr/bin/pythonlist1,

list2 = [123, 'xyz', 'zara']

参考资料:Python-百度百科

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-10-03

参考代码:

list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c"];
len(list1)
len(list2)
len(list3)

Python支持列表切割(list slices),可以取得完整列表的一部分。支持切割操作的类型有str, bytes, list, tuple等。它的语法是...[left:right]或者...[left:right:stride]。假定nums变量的值是[1, 3, 5, 7,],那么下面几个语句为真:

nums[2:5] == [5, 7] 从下标为2的元素切割到下标为5的元素,但不包含下标为5的元素。

nums[1:] == [3, 5, 7] 切割到最后一个元素。

nums[:-3] == [1, 3, 5, 7] 从最开始的元素一直切割到倒数第3个元素。

nums[:] == [1, 3, 5, 7] 返回所有元素。改变新的列表不会影响到nums。

nums[1:5:2] == [3, 7] 从下标为1的元素切割到下标为5的元素但不包含下标为5的元素,且步长为2。

扩展资料:

Python 是一门有条理的和强大的面向对象的程序设计语言,类似于Perl, Ruby, Scheme, Java。

Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读、易维护,并且被大量用户所欢迎的、用途广泛的语言。

设计者开发时总的指导思想是,对于一个特定的问题,只要有一种最好的方法来解决就好了。这在由Tim Peters写的Python格言(称为The Zen of Python)里面表述为:There should be one-- and preferably only one --obvious way to do it. 这正好和Perl语言(另一种功能类似的高级动态语言)的中心思想TMTOWTDI(There's More Than One Way To Do It)完全相反。

Python的作者有意的设计限制性很强的语法,使得不好的编程习惯(例如if语句的下一行不向右缩进)都不能通过编译。其中很重要的一项就是Python的缩进规则。

参考资料:百度百科-Python

本回答被网友采纳
第2个回答  2014-11-24

以下代码测试通过:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
inFile, outFile = r'a.txt', r'b.txt'
with open(inFile, 'r') as f1:
    with open(outFile, 'w') as f2:
        for n, line in enumerate(f1):
            size = len(line[:-1].split(' '))
            if size > 5:
                f2.write("%s %s\n" % (str(n+1), str(size)))

 

如果是在Windows上跑,就去掉第一行。

本回答被提问者采纳
第3个回答  2014-11-24
#!/usr/bin/env python

f=open('a.txt')
d=f.readlines()
f.close()
con=1

w=open('b.txt','w')
for i in d:
if len(i.split()) > 5 :
b="%s %s\n" %(con,len(i.split()))
w.write(b)
con = con + 1
w.close()

不明白的地方可以问
第4个回答  2015-07-01
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c"];
len(list1)
len(list2)
len(list3)
相似回答