简体   繁体   中英

numbers string of list separated with space in Python

I have a txt file that read line by line and the text file has some data as below. I am trying to extract the numbers so that I can process them as in array of something like that. The space in between dates and the start of the numbers are 'tabs" and the numbers have normal spaces.

04/10/2000 02 75 30 54 86
04/16/2000 63 63 48 32 12
04/15/2000 36 47 68 09 40
04/14/2000 06 27 31 36 43
04/13/2000 03 08 41 60 87

Here is the code I wrote:

    for line in handle:
       line = line.rstrip()
       numberlist.append(line.split('\t'))

   numbers=list()   
   numberlist=list()
   for x in numberlist:
       numbers.append(x[1]) 

   print(numbers[:2]) # just to see sample output 

Could someone help me to figure out? I checked some python tutorial even but the more I think about the issue, the more tricky and detailed it seems to me. (please note that this is not a homework)

Thanks

You can split on a tab \t to get 2 parts. Then split the second part on a space to get all the numbers.

strings = [
    "04/10/2000 02 75 30 54 86",
    "04/16/2000 63 63 48 32 12",
    "04/15/2000 36 47 68 09 40",
    "04/14/2000 06 27 31 36 43",
    "04/13/2000 03 08 41 60 87"
]

numbers = list()
numberlist = list()

for s in strings:
    lst = s.rstrip().split("\t")
    if len(lst) > 1:
        lst = lst[1].split(" ")
        numberlist.append(lst)
        for n in lst:
            numbers.append(n)

print(numbers)
print(numberlist)

Output

['02', '75', '30', '54', '86', '63', '63', '48', '32', '12', '36', '47', '68', '09', '40', '06', '27', '31', '36', '43', '03', '08', '41', '60', '87']
[['02', '75', '30', '54', '86'], ['63', '63', '48', '32', '12'], ['36', '47', '68', '09', '40'], ['06', '27', '31', '36', '43'], ['03', '08', '41', '60', '87']]

Python demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM