Skip to main content
 首页 » 编程设计

python之将文本文件中的第一列数据转换为python中的列表

2025年05月04日12youxin

我想将文本文件的第一列数据转换成python中的列表

data = open ('data.txt', 'r') 
data.read() 

提供

'12 45\n13 46\n14 47\n15 48\n16 49\n17 50\n18 51' 

请帮忙。

请您参考如下方法:

您可以在此处使用 str.split 和 list comprehension:

with open('data.txt') as f: 
   lis = [int(line.split()[0]) for line in f] 
>>> lis 
[12, 13, 14, 15, 16, 17, 18] 

如果数字是字符串:

>>> with open('abc') as f: 
       lis = [line.split()[0] for line in f] 
>>> lis 
['12', '13', '14', '15', '16', '17', '18'] 

简化版:

>>> with open('abc') as f:     #Always use with statement for handling files 
...     lis = [] 
...     for line in f:         # for loop on file object returns one line at a time 
...         spl = line.split() # split the line at whitespaces, str.split returns a list 
...         lis.append(spl[0]) # append the first item to the output list, use int() get an integer 
...     print lis     
...      
['12', '13', '14', '15', '16', '17', '18'] 

关于 str.split 的帮助和示例:

>>> strs = "a b c d ef gh i" 
>>> strs.split()  
['a', 'b', 'c', 'd', 'ef', 'gh', 'i'] 
>>> print str.split.__doc__ 
S.split([sep [,maxsplit]]) -> list of strings 
 
Return a list of the words in the string S, using sep as the 
delimiter string.  If maxsplit is given, at most maxsplit 
splits are done. If sep is not specified or is None, any 
whitespace string is a separator and empty strings are removed 
from the result.