如何在一个任意列表中找到出现在另一个列表中的元素(保持其顺序)?

2024-04-20 04:50:36 发布

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

我需要创建一个算法来读取列表AB的用户输入,并确定列表B中的元素是否出现在列表A中(如果出现,程序需要打印“Yes”,否则打印“No”)。你知道吗

我提出了以下代码,可以作为一个起点:

n=int(input('Enter the length of list A '))
A=[]
for i in range (0,n):
    InpEl=int(input('Enter the elements '))
    A.append(InpEl)
print(A)
n=int(input('Enter the length of list B '))
B=[]
for i in range (0,n):
    InpEl2=int(input('Enter the elements '))
    B.append(InpEl2)
print(B)

checklist=B
for each in A:
    if each in checklist:
        print('YES')
    else:
         print('NO')

不管怎样,我都会说“不”。这里出了什么错?你知道吗

另外,稍后我可能需要修改列表,以便程序可以确定B的元素是否按照它们在B中出现的顺序出现在A,但不一定是连续出现的。你知道吗

For example, let M be the length of B and N be the length of A.
Then the program should return yes if there are indices i0, i1...im+1 such that 0<= i0 < i1...< im-1 < N such that A[i0] = B[0];A[i1] = B[1]...A[im-1] =
B[m-1].

有没有更简单的方法来构建满足这种请求的循环?你知道吗

附言:是否可以让用户输入不仅读取整数,而且读取字符串?我不确定raw_input在python3.5中是否有用。你知道吗

附言: 对不起,我在这里输入代码时犯了一个小错误,我现在已经改正了。 另一个问题:我得到每个元素的多个“是”和“否”的输出:

Enter the length of list A 3
Enter the elements 1
Enter the elements 2
Enter the elements 3
[1, 2, 3]
Enter the length of list B 3
Enter the elements 5
Enter the elements 4
Enter the elements 3
[5, 4, 3]
NO
NO
YES

如何修改代码,以便在发生任何错误时只打印一次“是”和“否”?你知道吗


Tags: oftheno代码in元素列表for
2条回答

你得到的一个武器是all操作符,它只检查iterable中的所有项是否为真:

A = [1, 4, 6, 8, 13]
B = [4, 6, 13, 8]
C = [3, 8, 25]

master = [i for i in range(20)]

print all(i in master for i in A)
print all(i in master for i in B)
print all(i in master for i in C)

输出:

True
True
False

为了获得顺序,您需要返回到一个迭代方法,使用循环遍历第一个列表,同时维护一个索引以知道您在第二个列表中的位置。对于第一个列表中的每个值,遍历第二个列表的rest,直到找到项目(临时成功)或到达末尾(失败)。你知道吗

读入数字名并将其转换为整数是一个单独的问题,而且代码较长。你知道吗

这里有一个解决方案。请记住,有很多人以前问过这类问题,最好的做法是在问之前四处搜索。你知道吗

a = input('enter list A with comma between each element: ')
b = input('enter list B with comma between each element: ')

a = a.split(',')
b = b.split(',')

contained_in_b = [element in b for element in a]

for i, in_b in enumerate(contained_in_b):
    print('element {} contained in list B: {}'.format(a[i], in_b))

最好将原始输入放在一起,并使用Python将其拆分为列表。这样,用户就不需要事先给出列表的长度。而且,不需要转换成int字符串比较也可以。你知道吗

contained_in_b使用列表理解-Python的一个便利特性,它将布尔值element in b应用于a中的每个element。现在您有了一个真/假值列表,您可以通过它enumerate打印出所需的输出。你知道吗

相关问题 更多 >