From: Yongwei Xing on
Hi all

I have a txt file like below:

1 2 3 4 5 6
2 3 4 5 6 7
8 9 1 7 6 7
4 5 6 1 4 7

How can I read these data into a nested list? If the data is string or
char, is there any difference to do it?

Best Regards,
From: Tamas K Papp on
On Thu, 20 May 2010 01:41:46 -0700, Yongwei Xing wrote:

> Hi all
>
> I have a txt file like below:
>
> 1 2 3 4 5 6
> 2 3 4 5 6 7
> 8 9 1 7 6 7
> 4 5 6 1 4 7
>
> How can I read these data into a nested list? If the data is string or
> char, is there any difference to do it?

(defun read-matrix-line (string)
(with-input-from-string (stream string)
(loop
for line = (read stream nil nil)
while line
collecting line)))

(defun read-matrix (stream)
(loop
for line = (read-line stream nil nil)
while line
collecting (read-matrix-line line)))

Then if your data is in a string, do

(defparameter *string*
"1 2 3 4 5 6
2 3 4 5 6 7
8 9 1 7 6 7
4 5 6 1 4 7")

(with-input-from-string (stream *string*)
(read-matrix stream))

For a file, see WITH-OPEN-FILE.

Also, note that the lists-in-list representation is not the most
efficient if you are doing anything serious with matrices. Use arrays,
or one of the computational libraries.

Best,

Tamas
From: Giovanni Gigante on

> How can I read these data into a nested list?

apply SPLIT-SEQUENCE on each line.
http://www.cliki.net/SPLIT-SEQUENCE
From: Pascal J. Bourguignon on
Yongwei Xing <jdxyw2004(a)gmail.com> writes:

> Hi all
>
> I have a txt file like below:
>
> 1 2 3 4 5 6
> 2 3 4 5 6 7
> 8 9 1 7 6 7
> 4 5 6 1 4 7
>
> How can I read these data into a nested list? If the data is string or
> char, is there any difference to do it?

Here's the lazy lisper solution:

(defun read-matrix (stream)
(loop
for line = (read-line stream nil nil)
while line
collect (read-from-string (concatenate 'string "(" line ")"))))

(with-input-from-string (example " 1 2 3 4 5 6
2 3 4 5 6 7
8 9 1 7 6 7
4 5 6 1 4 7
")
(read-matrix example))
--> ((1 2 3 4 5 6)
(2 3 4 5 6 7)
(8 9 1 7 6 7)
(4 5 6 1 4 7))

If your lines are not too long (eg. if they can be kept in a few L1
cache lines), time and space complexity will be dominated by
READ-FROM-STRING time, and CONCATENATE will be peanuts.

--
__Pascal Bourguignon__
http://www.informatimago.com
From: Aleksander Nabagło on
Yongwei Xing pisze:
> Hi all
>
> I have a txt file like below:
>
> 1 2 3 4 5 6
> 2 3 4 5 6 7
> 8 9 1 7 6 7
> 4 5 6 1 4 7
>
> How can I read these data into a nested list? If the data is string or
> char, is there any difference to do it?
Use array of arrays.
Reformat lispy way and read again:

;;;

(defun mtx-read (f)
(read-from-string
(with-output-to-string (s)
(princ "#(" s)
(flet ((rd () (read-line f nil nil)))
(do ((g (rd) (rd)))
((or (null g)
(every #'(lambda (x) (not (digit-char-p x))) g)))
(format s "~A~A~A" "#(" g ")"))
(princ ")" s)))))

(with-open-file (f "m.dat" :direction :input)
(print (mtx-read f)))


;;;

--
A
..
 |  Next  |  Last
Pages: 1 2
Prev: PAY PER CLICK
Next: Unexpected relative performance