python - 我只需要所选选择的结果,但它会显示所有其他结果以及任何选择
问题描述
#purpose - program to perform some list operations
list1 = []
list2 = []
print("Select operation.")
print("1.Check Length of two list's are Equal")
print("2.Check sum of two list's are Equal")
print("3.whether any value occur in both ")
print("4.Display Lists")
while True:
choice = input("Enter any choice ")
if choice in ('1', '2', '3', '4'):
list1Len = int(input("Enter the number of elements in list 1 : "))
for i in range(0, list1Len):
print("Enter the element ", i+1, ":")
item1 = int(input())
list1.append(item1)
list2Len = int(input("Enter the number of elements in list 2 : "))
for j in range(0, list2Len):
print("Enter the element ", j+1, ":")
item2 = int(input())
list2.append(item2)
if choice == '1' and len(list1) == len (list2):
print(" Length are Equal")
else :
print(" Length are Not Equal")
if choice == '2'and sum(list1) == sum (list2):
print(" Sums are Equal")
else :
print(" Sums are Not Equal")
if choice == '3':
list3 =[x for x in list1 if x in list2][enter image description here][1]
print("Common elements in both list are \n", list3)
if choice == '4':
print( "List 1 is :\n",list1 ,"List 2 is :\n", list2)
我只需要选定选项的结果,但它显示所有其他结果,任何选项它显示我包含在代码中的所有操作,如何修复它,我提供了一个图像。
希望我说得足够清楚......
解决方案
该代码完全按照您的要求执行:检查四个选项中的每一个。即使它不是正确的选择,您也会打印失败消息。您需要将逻辑嵌套在两个级别:一个用于确定正确的选择,另一个用于确定正确的响应。
if choice == '1':
if len(list1) == len (list2):
print(" Length are Equal")
else:
print(" Length are Not Equal")
elif choice == '2':
if sum(list1) == sum (list2):
print(" Sums are Equal")
else:
print(" Sums are Not Equal")
... 等等
推荐阅读
- ios - iPhone 进入睡眠状态时继续获取加速度计数据
- c# - 如何从 C# 中的 Async 方法读取返回值?
- html - 使 div css 宽度 1366px 高度 768px 适合父 div
- c - 以这种方式解决编译时的链表创建问题
- javascript - 为元素的子元素着色
- extjs - Extjs 绑定值没有被清除
- generics - DI,具有抽象、通用父级的具体类
- excel - 使用 Google AppScript 将 .csv 文件转换为 .xls
- h.264 - 编码器中使用的 fixed_frame_rate_flag 是什么?
- angular - Angular CanActivate 在浏览器刷新时失败,即使 observable 返回 true