首页 > 解决方案 > 为什么比较在python中的if条件下不起作用?

问题描述

Q1。给定一个整数数组,如果 6 作为数组中的第一个或最后一个元素出现,则返回 True。数组长度为 1 或更大。

#first_last6([1, 2, 6]) → True
#first_last6([6, 1, 2, 3]) → True
#first_last6([13, 6, 1, 2, 3]) → False

#Code
my_list = []
in_list = list(map(int, input("Enter a multiple value: ").split()))
for num in in_list:
    my_list.append(num)
if (my_list[0:] == 6 or my_list[:-1] == 6):
    print("True")
else:
    print("False")

代码运行良好,但如果条件不起作用而 else 运行良好,就像我们在 else 语句中访问索引“in_list [2]”一样,它将给出正确的答案。那为什么如果条件不起作用呢?

标签: pythonarraysfor-loopif-statementarraylist

解决方案


摆脱:.

这就是slice符号,切片的结果是一个列表,而不是该列表的元素。

my_list = [6, 1, 2, 3]
print(my_list[0:], my_list[:-1]) # slice list
print(my_list[0],  my_list[-1])  # access list item by index

输出:

[6, 1, 2, 3] [6, 1, 2]
6 3

推荐阅读