简体   繁体   English

将列表转换为 python 列表的最快方法是什么?

[英]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.

相关问题 在python中查找列表中列表元素的最快方法是什么? - What's the fastest way to locate a list element within a list in python? 在 Python 中将字典频率转换为列表的最快方法是什么? - What is the fastest way to convert a dictionary frequency to list in Python? 在Python 2.7中保存/加载大型列表的最快方法是什么? - What's the fastest way to save/load a large list in Python 2.7? 在 Python 2.7 中序列化和反序列化对象列表的最快方法是什么? - What's the fastest way to serialize and deserialize a list of objects in Python 2.7? 在 Python 中清空列表的最快方法是什么 - what is the fastest way to empty a list in Python 将迭代器转换为列表的最快方法 - Fastest way to convert an iterator to a list 在 Python 中迭代列表并找到合适的字符串模式的最快(最有效)方法是什么? - What's the fastest (most efficient) way to iterate through a list and find a fitting string pattern in Python? 在Python 3.6中保存/加载大量字符串(列表/集合)的最快方法是什么? - What's the fastest way to save/load a large collection (list/set) of strings in Python 3.6? 使用 Python 从列表中消除字符串的所有实例的最快方法是什么? - What's the fastest way to eliminate all instances of a string from a list with Python? 在 Python 列表中大量查找随机索引的最快方法是什么? - What's the fastest way of finding a random index in a Python list, a large number of times?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM