我想知道如何从数组列表中快速访问字典的值。
下面是我的玩具例子:
my_list = [np.array([ 1, 2, 3, 4, 5, 6, 8, 9, 10]), np.array([ 1, 3, 5, 6, 7, 10]), np.array([ 1, 2, 3, 4, 6, 8, 9, 10]), np.array([ 1, 3, 4, 7, 15]), np.array([ 1, 2, 4, 5, 10, 16]), np.array([6, 10, 15])]
my_dict = {1: 0, 2: 0, 3: 0, 4: 0, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 3, 16: 3}
字符串
- *my_dict中的每个键对应于名为my_list**的列表中的值
我使用以下代码来获得所需的输出集:
unique_string_parents = {' '.join(map(str, set(map(my_dict.get, sublist)))) for sublist in my_list}
# output: {'0 1 2', '0 1 3', '0 1 2 3', '1 2 3'}
型
假设我有一个很大的维度my_list和my_dict,可以在这里找到:https://gitlab.com/Schrodinger168/practice/-/tree/master/practice_dictionary
下面是读取真实的文件的代码:
import ast
file_list = 'list_array.txt'
with open(file_list, 'r') as file:
lines = file.readlines()
my_list= [np.array(list(map(int, line.split()))) for line in lines]
file_dictionary = "dictionary_example.txt"
with open(file_dictionary, 'r') as file_dict:
content = file_dict.read()
my_dict = ast.literal_eval(content)
型
我使用了上面提供的一行代码;大约需要16.70秒才能得到所需的输出。我想知道如何加快这个算法,或者有没有其他算法可以让我在这种情况下更快地得到结果?
任何帮助或建议,请!非常感谢!
1条答案
按热度按时间9w11ddsr1#
看看你的代码和
my_dict
,我认为你应该使用np.array
而不是字典。另外,在结尾处将数字转换为字符串:字符串
打印:
型
编辑:与您的文件张贴在问题中,你可以尝试(在我的机器上,这需要11秒对19秒的原始答案):
型
编辑2:两种方法的比较:
型
打印:
型