Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于条件从列表中删除元素_Python_Python 3.x - Fatal编程技术网

Python 基于条件从列表中删除元素

Python 基于条件从列表中删除元素,python,python-3.x,Python,Python 3.x,我需要根据另一个列表中的条件(如果满足)从一个列表中删除一个元素(在本例中是一个元组) 我有两个列表(元组列表) 清单1基本上由以下代码计算得出 import pandas as pd mapping = {'name': ['a', 'b', 'c', 'd'],'ID': [1,2,3,2]} df = pd.DataFrame(mapping) comb = df['name'].to_list() List1 = list(combinations(comb,2)) # ma

我需要根据另一个列表中的条件(如果满足)从一个列表中删除一个元素(在本例中是一个元组)

我有两个列表(元组列表)

清单1基本上由以下代码计算得出

import pandas as pd    
mapping = {'name': ['a', 'b', 'c', 'd'],'ID': [1,2,3,2]} 
df = pd.DataFrame(mapping)
comb = df['name'].to_list()
List1 = list(combinations(comb,2))

# mapping the elements of the list to an 'ID' from the dataframe and creating a list based on the following code
List2 = [(df['ID'].loc[df.name == x].item(), df['ID'].loc[df.name == y].item()) for (x, y) in List1]
现在我需要在这里应用一个条件;查看列表2,我需要查看列表2中的所有元组,并查看其中是否有具有相同ID的元组。例如,在列表2中,我看到有(2,2)。因此,我想基于此返回到列表1,删除生成此(2,2)对的对应元组

基本上,我的最终修订清单如下:

RevisedList = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('c', 'd')]
('b','d')应该被删除,因为它们在一个集合中产生(2,2)个相同的ID

List1 = [('a','b'), ('a','c'), ('a','d'), ('b','c'), ('b','d')]
List2 = [(1,2), (1,3), (1,2), (2,3), (2,2)]
new_List1 = [elem for index,elem in enumerate(List1) if List2[index][0]!=List2[index][1]]
// Result: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c')]

现在还不完全清楚,但这就是你想要的吗?new_List1只包含那些索引,在该索引处,List2在元组中有两个不同的数字

List1是元组列表,而List2是元组列表,对吗?另外,在questionList2中添加输入的预期输出也是一个元组列表,如[(1,2),(1,3),(1,2),(2,3),(2,2),(3,2)]修复问题以反映这一点,预期输出是什么?你们说(2,2)在to和('b','d')的列表中是相同的,为什么('b','c')或('a','b')不去呢?请解释得更清楚些。很难理解身份证和字母之间的关系。如果
b
2
为什么
(2,2)
对应
(b,d)
而不是
(b,b)
。您只想删除列表1中与列表2中具有相同成员的元组相对应的元素吗?当然@DeveshKumarSingh我现在就解决这个问题。我将对问题进行编辑,使其更清楚
List1 = [('a','b'), ('a','c'), ('a','d'), ('b','c'), ('b','d')]
List2 = [(1,2), (1,3), (1,2), (2,3), (2,2)]
new_List1 = [elem for index,elem in enumerate(List1) if List2[index][0]!=List2[index][1]]
// Result: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c')]