簡體   English   中英

將文本文件的第一列數據轉換為python中的列表

[英]convert first column of data from text file into a list in python

我想將數據的第一列從文本文件轉換為python中的列表

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

提供

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

請幫忙。

您可以在此處使用str.splitlist comprehension str.split

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.
import csv
with open ('data.txt', 'rb') as f:
    print [row[0] for row in csv.reader(f, delimiter=' ')]

['12', '13', '14', '15', '16', '17', '18']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM