[英]Using index from a list to get another value/element in another list
I have project wherein I have to get the index of certain element in a list, then use that index to get another value in another list.我有一个项目,其中我必须获取列表中某个元素的索引,然后使用该索引在另一个列表中获取另一个值。
For example,例如,
j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
on_going = [1]
e_list = [[], [1], [1], [2], [3], [3], [5], [4, 7], [6], [8, 9], [10]]
So far, the code looks like this:到目前为止,代码如下所示:
if isinstance(on_going, int):
on_going = [on_going]
idx = [y for y, x in enumerate(e_list) if x in on_going] # code to get index in e_list
print(idx)
for i in idx:
q_active = j_set.append(i)
print(q_active)
The objective is to get the corresponding index
of value/element in on_going
from e_list
.目标是从
e_list
获取on_going
中值/元素的相应index
。 Then, use that index to get corresponding activity from j_set
and store in q_active
.然后,使用该索引从
j_set
获取相应的活动并存储在q_active
中。
Expected output:
q_active = [2, 3]
The problem is, with the code above, I am getting an output for storing values in q_active as:问题是,使用上面的代码,我得到一个 output 用于将值存储在 q_active 中:
[1, 2] #idx output
None
None
Any help would be appreciated!任何帮助,将不胜感激! Thanks!
谢谢!
You can use enumerate
to get index and data from list:您可以使用
enumerate
从列表中获取索引和数据:
e_list = [[], [1], [1], [2], [3], [3], [5], [4, 7], [6], [8, 9], [10]]
for data_index, data_val in enumerate(e_list):
print(data_index, data_val)
# write business logic here
Perhaps use a list_comprehension:也许使用 list_comprehension:
print([j_set[item] for i in on_going for item in range(len(e_list)) if i in e_list[item]])
#[2, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.