[英]Fastest way to convert a string with many integers into a list distinct integers
我有一个字符串,其中包含许多用逗号分隔的整数。 我正在尝试转换此字符串(类似于csv_data = "1,23,543,12,423,534,76,32,765,23,12,1,43,213,6,5"
)
到不同的 integer 值列表中。 csv_values = [1,23,543,12,423,534,76,32,765,23,12,1,43,213,6,5]
我尝试的第一个想法是 for 循环,但我知道这不是进行转换的最快方法
l = []
for ch in csv_data:
if ch != ',':
l.append(int(ch))
有任何想法吗?
使用标准库和 pandas。
from ast import literal_eval
import pandas as pd
import numpy as np
string = "1,23,543,12,423,534,76,32,765,23,12,1,43,213,6,5"
list(literal_eval(string))
[1, 23, 543, 12, 423, 534, 76, 32, 765, 23, 12, 1, 43, 213, 6, 5]
pd.eval(string)
array([1, 23, 543, 12, 423, 534, 76, 32, 765, 23, 12, 1, 43, 213, 6, 5],
dtype=object)
然后,您可以使用np.unique
或仅set
来获取不同的整数。
np.unique(pd.eval(string))
array([1, 5, 6, 12, 23, 32, 43, 76, 213, 423, 534, 543, 765], dtype=object)
或者
list(set(literal_eval(string)))
[32, 1, 5, 6, 423, 43, 12, 76, 213, 534, 23, 765, 543]
请注意, np.unique
将对您的值进行排序。
一些天真的时机,
string2 = string * 1000
%%timeit
list(set(literal_eval(string2)))
34 ms ± 1.55 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
np.unique(pd.eval(string2))
494 ms ± 12.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
使用它首先将其转换为列表
def Convert(string):
li = list(string.split("-"))
return li
如果你有一个字符串,你可以使用[int(x) for x in csv_data.split(',')]
If the data actually comes from a file, use one of the already-existing functions to read a csv file, either the built-in csv
module or the Pandas read_csv
function .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.