a method of combining vertical numbers into a single list

Asked 2 years ago, Updated 2 years ago, 37 views

1
2
3
4
5
6
7
8
9
10

with the words
[1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
I'd like to convert to , what should I do?

python python3

2022-09-30 16:51

2 Answers

If this number is written in the text file in.txt, it will be substituted for the list data by writing:

with open('in.txt', 'r') as f:
    data = [ ]
    line=f.readline()# Read line 1
    while line:
        Exclude data.append(line.rstrip())#line because it also contains newline characters
                                    # (Note that this excludes blank characters.)
        line=f.readline()# Read the next line


2022-09-30 16:51

This is a one-liner solution for external file entry.

import sys

data = [n.trip() for n in sys.stdin.readlines()]
print(data)

Behavioral Demo: https://wandbox.org/permlink/pr6r7UrTzkU8rRhj


2022-09-30 16:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.