[英]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?将其转换为 python 列表语法的最快方法是什么?
[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.其中
L
是列表。
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.