I have a list and 2d list that I would like to return only the matching values. For instance I have number 10 that I would like to find a match in df2.
我有一个列表和2d列表,我想只返回匹配的值。例如,我有一个数字10,我想在df2中找到一个匹配项。
Df1 = [10]
Df2 = [[2,4],[5,10,13,],[2,3],
[2,6,10,20]]
Expected Output
预期输出
Df3 = [[5,10,10,13],
[2,6,10,10,20]]
更多回答
what are we supposed to do, if we have more than one element in DF1?
如果DF1中有多个元素,我们该怎么办?
You forgot to post the code you're having difficulty with
你忘了发布你遇到困难的代码
Can you clarify if Df1
can contain more than one element? If yes what should happen? And why do you have twice the searched item in the output? Do you want to insert it? Are the list always sorted? Can you have more than once the same item?
你能澄清一下Df1是否可以包含多个元素吗?如果是,该怎么办?为什么在输出中有两次搜索的项目?你想插入它吗?列表总是排序的吗?同一件物品你能拥有不止一次吗?
You could use set
operations to check if any item is common:
您可以使用set操作来检查是否有任何项目是通用的:
S = set(Df1)
out = [l for l in Df2 if S.intersection(l)]
Output:
输出:
[[5, 10, 13], [2, 6, 10, 20]]
If you have several items and want to match all:
如果您有多个项目并希望全部匹配:
Df1 = [10, 13]
S = set(Df1)
out = [l for l in Df2 if S.issubset(l)]
Output:
输出:
[[5, 10, 13]]
There must be better ways but here you go:
肯定有更好的方法,但你来吧:
Df3 = []
for x in Df1:
for sub_list in Df2:
if x in sub_list:
Df3.append(sub_list)
Note that the output is [[5, 10, 13], [2, 6, 10, 20]]
, not [[5,10,10,13], [2,6,10,10,20]]
请注意,输出是[[5,10,13],[2,6,10,20]],而不是[[5,10,10,13],[2,6,10,10,20]]
Here's yet another way using nested for loops (to allow for Df1 containing more than one element):
以下是使用嵌套for循环的另一种方法(允许Df1包含多个元素):
Df1 = [10]
Df2 = [
[2,4],
[5,10,13],
[2,3],
[2,6,10,20]
]
Df3 = []
for m in Df1:
for e in Df2:
try:
i = e.index(m)
(_e := e[::]).insert(i, m)
Df3.append(_e)
except ValueError:
pass
print(Df3)
Output:
输出:
[[5, 10, 10, 13], [2, 6, 10, 10, 20]]
更多回答
Looks like he also inserts the element that he is checking for, so maybe sub_list.append(x)
and sub_list.sort()
could be added.
看起来他还插入了他正在检查的元素,所以也许可以添加sub_list.append(x)和sub_list.sort()。
我是一名优秀的程序员,十分优秀!