【发布时间】:2017-05-07 08:18:30
【问题描述】:
我需要创建一个算法来读取列表A 和B 的用户输入并确定列表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