简体   繁体   中英

What's the fastest way to convert a list into a python list?

Say I have a list like such:

1
2
3
abc

What's the fastest way to convert this into python list syntax?

[1,2,3,"abc"]

The way I currently do it is to use regex in a text editor. I was looking for a way where I can just throw in my list and have it convert immediately.

Read the file, split into lines, convert each line if numeric.

# Read the file
with open("filename.txt") as f:
    text = f.read()

# Split into lines
lines = text.splitlines()

# Convert if numeric
def parse(line):
    try:
        return int(line)
    except ValueError:
        return line

lines = [parse(line) for line in lines]

If it's in a text file like you mentioned in the comments then you can simply read it and split by a new line. For example, your code would be:

with open("FileName.txt", "r") as f:
    L = f.read().split("\n")

print(L)

Where L is the list.

Now, if your looking for the variables to be of the correct type instead of all being strings, then you can loop through each in the list to check. For example, you could do the following:

for i in range(len(L)):
    if L[i].isnumeric():
        L[i] = int(L[i])

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