两个列表元素之间的关系:如何在Python中利用它?

2024-09-29 05:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的最小工作示例:

# I have a list
list1 = [1,2,3,4]
#I do some operation on the elements of the list
list2 = [2**j for j in list1]
# Then I want to have these items all shuffled around, so for instance
list2 = np.random.permutation(list2)

#Now here is my problem: I want to understand which element of the new list2 came from which element of list1. I am looking for something like this:

list1.index(something)

# Basically given an element of list2, I want to understand from where it came from, in list1. I really cant think of a simple way of doing this, but there must be an easy way!

你能给我一个简单的解决办法吗?这是一个最小的工作示例,但是主要的一点是我有一个列表,我对元素执行一些操作,并将这些元素分配给一个新的列表。然后所有的东西都乱丢了,我需要弄清楚它们是从哪里来的。你知道吗


Tags: ofthetoinfrom示例whichfor
3条回答

枚举,就像大家说的那样是最好的选择,但是如果你知道映射关系,还有一个选择。您可以编写一个与映射关系相反的函数。(例如,如果原始函数编码,则解码。) 然后使用decoded_list = map(decode_function,encoded_list)获得一个新列表。然后把这个清单和原来的清单交叉比较,你就可以实现你的目标了。你知道吗

如果您确定相同的列表是使用编码中的encode_函数修改的,则Enumerate更好。 然而,如果你是从其他地方导入这个新列表,例如从网站上的一个表导入,我的方法是正确的。你知道吗

根据您的代码:

# I have a list
list1 = [1,2,3,4]
#I do some operation on the elements of the list
list2 = [2**j for j in list1]
# made a recode of index and value
index_list2 = list(enumerate(list2))
# Then I want to have these items all shuffled around, so for instance
index_list3 = np.random.permutation(index_list2)
idx, list3 = zip(*index_list3)

#get the index of element_input in list3, then get the value of the index in idx, that should be the answer you want.
answer = idx[list3.index(element_input)]

您可以使用排列列表/索引:

# I have a list
list1 = [1,2,3,4]
#I do some operation on the elements of the list
list2 = [2**j for j in list1]
# Then I want to have these items all shuffled around, so for instance
index_list = range(len(list2))
index_list = np.random.permutation(index_list)
list3 = [list2[i] for i in index_list]

然后,用input_element

answer = index_list[list3.index(input_element)]

相关问题 更多 >