【问题标题】:How to find elements in one arbitrary list that occur in another list (preserving their order)?如何在一个任意列表中找到另一个列表中出现的元素(保持它们的顺序)?
【发布时间】:2017-05-07 08:18:30
【问题描述】:

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

我想出了以下代码,应该可以作为起点:

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].

是否有更简单的方法来构建满足此类请求的循环?

P.S.:是否可以让用户输入不仅读取整数,还读取字符串?我不确定raw_input 在 Python 3.5 中是否有用。

附: 对不起,我在这里输入代码时犯了一个小错误,我现在修复它。 另一个问题:我得到了每个元素的多个 yes 和 no 的输出:

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

如何修改代码,以便在发生任何情况时只打印一个 yes 和 no 一次?

【问题讨论】:

  • checklist = B 不是[B]
  • “让用户输入不仅读取整数,还读取字符串?” - 什么?您将字符串显式转换为整数。也许......不要?
  • checklist=[B] 使 B 成为名为 checklist 的新列表中的嵌套列表(该列表将仅包含 一个 元素,即整个 B 列表)。
  • @jonrsharpe 我的意思是用户可以输入例如 1 和 'one',并且不会弄乱代码的执行
  • 如果你想知道如何将单词解析成数字,你需要做一些研究;这不是标准库中内置的。

标签: python list list-processing


【解决方案1】:

这是一种解决方案。请记住,以前有很多人问过这类问题,最佳做法是在问之前四处搜索。

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。现在您有了一个 True/False 值列表,您可以通过 enumerate 打印出所需的输出。

【讨论】:

    【解决方案2】:

    你得到的一个武器是 all 运算符,它只检查迭代中的所有项目是否为真:

    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,直到找到该项目(暂时成功)或结束(失败)。

    读取数字名称并将它们转换为整数是一个单独的问题,而且代码更长。

    【讨论】:

      猜你喜欢
      • 2015-06-09
      • 2019-10-28
      • 2023-02-01
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多