所以我会有两个这样的列表:
list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'xr']
所以我们可以说如果
案例 1:来自 list1 == 'p'
的项目我需要检查 '-p' 是否在 list2 中,或者,
案例 2:来自 list1== '-p'
的项目我需要检查 'p' 是否在 list2 上。
如果触发了任何这些情况,则从 list1 中删除该元素,这样我就只剩下仅以其否定形式出现或仅以其肯定形式出现的元素。现在我可以执行 CASE 1,但我不知道如何执行 CASE 2。
list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'xr']
new_list1 = list1.copy()
for y in list1:
for x in list2:
if x == '-'+y:
new_list1.remove(y)
对于这两个列表,只有当我处理这两种情况时才会留下
new_list1 = ['-q3']
现在我得到了这个:
new_list1 = ['-x', '-q3']
最佳答案
def toggle(x):
if x[0] == '-':
return x[1:]
else:
return '-'+x
list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'x']
new_list1 = list1.copy()
for y in list1:
for x in list2:
if x == toggle(y):
new_list1.remove(y)
这将为您提供new_list1 == ['-q3']
更省时的方式:
list1 = ['p', '-x', 'q123', '-q3']
list2 = ['p56', '-p', '-q123', 'x']
toggled_list2 = set(toggle(y) for y in list2)
new_list2 = list(set(list1).difference(toggled_list2))
# new_list2 == ['-q3']
关于python - 我需要比较两个列表并检查 list1 中的字符串是否在 list2 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64040258/